sort dict by value python [duplicate] sort dict by value python [duplicate] python python

sort dict by value python [duplicate]


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+


If you actually want to sort the dictionary instead of just obtaining a sorted list use collections.OrderedDict

>>> from collections import OrderedDict>>> from operator import itemgetter>>> data = {1: 'b', 2: 'a'}>>> d = OrderedDict(sorted(data.items(), key=itemgetter(1)))>>> dOrderedDict([(2, 'a'), (1, 'b')])>>> d.values()['a', 'b']


From your comment to gnibbler answer, i'd say you want a list of pairs of key-value sorted by value:

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