I'm trying to get a sorted dictionary. The dictionary should be sorted according to the following two criteria:
- According to the values (integers)
- If two keys (str) have the same value, sort alphabetically
So far, I have written the following line in my code:
sorted_word_values_dict = dict(sorted(word_values_dict.items(), key=operator.itemgetter(1)))
This code sorts correctly according to the first criteria, but if two keys (str) have the same value (e.g. both have a value of 2), they need to be sorted alphabetically. How can I include this extra criterium in my code?
Thanks in advance for any help!
CodePudding user response:
Given this dictionary:
d = {'c': 1251, 'b': 2372, 'f': 5172, 'a': 2372}
If you want to sort the values in ascending order and keys lexicographically:
out = dict(sorted(d.items(), key=lambda x: (x[1],x[0])))
Output:
{'c': 1251, 'a': 2372, 'b': 2372, 'f': 5172}
If however, you want to sort values in descending order (and keys lexicographically):
out = dict(sorted(d.items(), key=lambda x: (-x[1],x[0])))
Output:
{'f': 5172, 'a': 2372, 'b': 2372, 'c': 1251}
CodePudding user response:
You can use lambda as a key function in sorted call
Following should get you the new dict in sorted order -
sorted_word_values_dict = dict(sorted(word_values_dict.items(), key=lambda x: (x[1], x[0])))
The key argument in sorted function can take a function which returns multiple values, in case there is a tie between the first value, the comparison would move to next value in the key.
In this example, x[1](dict value) would be compared first, if it is identical, we would compare the x[0](dict key).
