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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With