Suppose you have a dictionary mydict, with key:value pairs mydict = {‘a’:5, ‘b’:2, ‘c’:1, ‘d’:6} You want to sort the keys by the values, maintaining the keys first in a list of tuples, so that the final list will be: [(‘c’,1), (‘b’,2), (‘a’,5), (‘d’,6)] aaaand, the stupid Python trick involves a nested list comprehension: sorted_list […]
Displaying posts tagged with
“lists”
Stupid Python tricks, #3296: sorting a dictionary by its values
By Iddo on April 3rd, 2013