How do I sort a dictionary by value using Python?

How do I sort a dictionary by value using Python ?

Hello Saanvi,

For Python 3.7+ or CPython 3.6, dictionaries preserve insertion order in Python 3.7+ and in CPython 3.6, although in the latter it’s considered an implementation detail.

You can sort a dictionary by its values using a dictionary comprehension with the sorted() function:

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_dict = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}

Or, you can use the dict() constructor with sorted() to achieve the same result:

sorted_dict = dict(sorted(x.items(), key=lambda item: item[1]))

For older Python versions where dictionaries are unordered, you can create a sorted representation of a dictionary by converting it to a list of tuples and then sorting that list. For example:

import operator

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_list = sorted(x.items(), key=operator.itemgetter(1))

To sort by keys instead of values, you can modify the key argument in sorted() or use operator.itemgetter(0):

sorted_list = sorted(x.items(), key=operator.itemgetter(0))

In Python 3, since unpacking in lambda is not allowed, you can use the following syntax:

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

Finally, if you want the output as an OrderedDict to preserve the order, you can use collections.OrderedDict:

import collections

sorted_dict = collections.OrderedDict(sorted_list)

Thank You

Hey Saanvi,

The approach is similar to Hank Gay’s answer:

sorted([(value, key) for (key, value) in mydict.items()])

An optimized version, as suggested by John Fouhy, can be used:

sorted((value, key) for (key, value) in mydict.items())

These expressions create a list of tuples where each tuple contains the value and key pairs from the dictionary mydict, which is then sorted based on the values.