Hi everyone
I’ve been trying to come up with the most efficient way to sort a dictionary by its values but since there aren’t any sorting methods for a dictionary, I’ve been struggling l to do so.
Any ideas? Thx
Since 3.7, dictionaries maintain insertion order. From
3.9 Documentation / Standard Library
:
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
So, to sort in value order:
extract a list or tuples of (key, value) pairs with the items() method.
swap the members in the tuples. You can use a list comprehension for this.
sort the list of swapped tuples.
swap the tupple members back using the same method as above.
use dict() to create a dictionary from the list of tupples
This will only work if your values are sortable.
dict
accepts an iterable of key/val pairs.
sorted
returns a list (an iterable) and also requires an iterable, but can also be provided with a key function to specify a metric to sort by, which can point to the value in a key/val pair. Try:
dict(sorted(d.items(), key = lambda item: item[1]))
You don’t have to do this explicitly, you could also directly sort on the items:
>>> dd1 = {'a': 3, 'b': 2, 'c': 1, 'd': 0}
>>> dd2 = dict(sorted(dd1.items(), key=lambda key_val: key_val[1]))
>>> print(dd2)
{'d': 0, 'c': 1, 'b': 2, 'a': 3}
Sorry - I missed the fact that @JamesParrott already posted this 
Roy Virzer:
does the the method items() return a tuple or a list? or a list inside a tuple?
An iterable of tuples. It’s not a list, but you can iterate over it and you’ll get tuples of (key, value) for everything in the dictionary.