# Sorting a dictionary by value in Python

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))``````

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)

Get only the best articles delivered to your mail

## ‘python’ is not recognized as an internal or external command, operable program or batch file.

Table of Contents Hide Set path during installationIf path size is largeSetting path using Environment Path windowRelated Posts: When you install python, sometimes you get this error – “‘python’ is…

## Pandas iterate over rows – Python

Python pandas provides iterrows() function which can be used to iterate over rows in dataframe. Consider this example – In order to iterate row by row, we need to run…

## ‘str’ object does not support item assignment – Python Error

You get Python error, ‘str’ object does not support item assignment, when you try to modify the string which is immutable in nature. Here is the thing, unlike languages like…

## Python convert bytes to string

If you want to convert bytes to string in Python, then you may use multiple ways of doing that. In this article, we are going to look at few methods.…

## ‘dict’ object has no attribute ‘iteritems’, ‘iterkeys’ or ‘itervalues’ – Python Error

Table of Contents Hide Why Python 3 removed iteritems()?Code ExampleLive DemoRelated Posts: Python throws error, ‘dict’ object has no attribute ‘iteritems’, because iteritems() function is removed from Python 3. Similarly,…

## Numpy random.rand to generate multidimensional random array in Python

Python Numpy random.rand can generate a multidimensional random array matrix of size equal to the provided input tuple. So, for example, if you provide (3,2) then it will generate a…