Sorting dictionary keys by value, then those with the same value alphabetically
Solution 1
I think that you want:
sorted(dictionary.items(), key=lambda t: t[::-1])
which is the same as:
def reverse_tuple(t):
return t[::-1]
sorted(dictionary.items(), key=reverse_tuple)
This works because tuples are sorted lexicographically. The first element is compared, if those are equal, python moves on to the second and so forth.
This is almost just sorted(dictionary.items())
unfortunately, then your primary sort order is determined by the first element in the tuples (i.e. the key) which isn't what you want. The trick is to just reverse the tuples and then the comparison works as you want it to.
Solution 2
This will do the trick:
sorted(dic.items(),key= lambda x: (x[1],x[0]))
It will be sorted in ascending order based on the second element(value of dictionary). If values of the dictionary are equal it will compare the first elements and sort them alphabetically. A better example to show this:
dic = {'abc':3, 'x':1, 'bcc':4, 'a':6 , 'bba':4 , 'bg':4 }
sorted:
[('x', 1), ('abc', 3), ('bba', 4), ('bcc', 4), ('bg', 4), ('a', 6)]
CharlieDeBeadle
Updated on June 12, 2022Comments
-
CharlieDeBeadle almost 2 years
I know it wasn't well explained in the title so I'll try and do a better job here. I want to sort a dictionary's keys by their respective values, and then sort any keys with the same value alphabetically. What is the best way to do this, ideally without the use of modules?
Does python do this automatically with a sort like:
sorted(dictionary.items(), key=lambda x: x[1])
I tried the above code and it seemed to work but I couldn't tell if it was just coincidence or not. I couldn't find anything in the docs and I need to know if it will always work.
Starting dictionary:
dictionary = {'d':2, 'c':1, 'a':2, 'b':3}
Sorted by value:
['c', 'd', 'a', 'b']
(1, 2, 2, 3)
Items with the same value sorted alphabetically:
['c', 'a', 'd', 'b']
(1, 2, 2, 3)
-
CharlieDeBeadle about 9 yearsCould you explain the difference? I'm really not very well versed such functions, "my" code was found on another question and copied when I saw it worked.
-
mgilson about 9 yearsYours simply looks at the element in the tuple at index 1 (i.e. the "value"). If two items have equal values, then the sorting algorithm thinks they're the same (for all intents and purposes) and puts them in the output in the same order that they came in (regardless of "key"). Mine takes the key into account only if the values are the same.