Alehud
Alehud

Reputation: 106

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

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.

Upvotes: 3

Views: 64

Answers (1)

Riccardo Bucco
Riccardo Bucco

Reputation: 15384

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.

Upvotes: 3

Related Questions