Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting lists as values in a dictionary (analogous to pandas.sort_values)

Tags:

python

I have a dictionary, where values are lists (of same size).

d = {'Name': ['archer', 'warrior', 'wizard', 'spearman'], 'Range': [10, 2, 10, 3], 'Strength': [4, 6, 8, 5]}

How can I sort the lists simultaneously, first based on 'Range' and then based on 'Strength'. The desired output is:

{'Name': ['warrior', 'spearman', 'archer', 'wizard'], 'Range': [2, 3, 10, 10], 'Strength': [6, 5, 4, 8]}

In pandas one could do this using pandas.sort_values, like this

df = pd.DataFrame(d)
df.sort_values(['Range', 'Strength'], inplace=True, ignore_index=True)

However, I want to do it directly in the dictionary.

like image 745
Alehud Avatar asked Jan 21 '26 20:01

Alehud


1 Answers

Here is a possible solution:

d['Range'], d['Strength'], d['Name'] = map(list,
                                           zip(*sorted(zip(d['Range'], 
                                                           d['Strength'],
                                                           d['Name']))))

Here you are basically creating a sequence of tuples (with zip)

((10, 4, 'archer'), (2, 6, 'warrior'), (10, 8, 'wizard'), (3, 5, 'spearman'))

Then you sort it, and finally you can reassign the values back to the dict keys.

like image 123
Riccardo Bucco Avatar answered Jan 23 '26 09:01

Riccardo Bucco