Sorting a dictionary by value in Python

Total
0
Shares

First of all, if sorting a dictionary by value is the frequent operation then you should consider using different data structure. But if your use case is to access data faster then dictionary is useful.

To sort a dictionary by value, you can use sorted() function. Here are some of the implementations –

Code Example 1:

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

Code Example 2:

>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

Code Example 3:

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

Code Example 4:

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

Code Example 5:

>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> def sk(n):  return n[1]
>>> sorted(x.items(), key=sk)

Code Example 6:

>>> from operator import itemgetter
>>> sorted(x.items(), key=itemgetter(1))

    Tweet this to help others

Code Example 6 is the best in terms of execution time. Check out live demo to get execution time of all 6 approaches.

Live Demo

Open Live Demo