sort dict by value python

kingRauk picture kingRauk · May 27, 2013 · Viewed 231.6k times · Source

Assume that I have a dict.

data = {1:'b', 2:'a'}

And I want to sort data by 'b' and 'a' so I get the result

'a','b'

How do I do that?
Any ideas?

Answer

John La Rooy picture John La Rooy · May 27, 2013

To get the values use

sorted(data.values())

To get the matching keys, use a key function

sorted(data, key=data.get)

To get a list of tuples ordered by value

sorted(data.items(), key=lambda x:x[1])

Related: see the discussion here: Dictionaries are ordered in Python 3.6+