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

Demo might not work in private window (incognito)

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles