Sorting a dict by its values

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

What do you want the output to be, a list? It can’t be a dict, since the dict will always be sorted by its keys.

Well, exactly, so I’m asking if there’s a way to take a dict, and print the same dict, just when it’s sorted by the values

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.

Ok, I’ll try. Thank you

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]))

3 Likes

Indeed. For pre 3.7 compatibility, I like a collections.OrderedDict (but note: dict(a=1, b=1) == dict( b=1, a=1), whereas: OrderedDict(a=1, b=1) != OrderedDict(b=1, a=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 :rofl:

1 Like

@ JamesParrott
dict accepts an iterable of key/val pairs.

Yours is a better solution if you want a stable sort. Mine sorts on the keys in cases of duplicate values.

What search terms did you use when you googled this? Googling your title easily found solutions for me…

ah now I see it, guess I wasn’t paying attentuon

Quick question, 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.

1 Like

Ok, Thank you

It used to return a list in Python 2, that was by no means a stupid question.

Laziness and iterators are more memory efficient.