By definition, dictionary are not sorted (to speed up access). Let us consider the following dictionary, which stores the age of several persons:

1 |
d = {"Pierre": 42, "Anne": 33, "Zoe": 24} |

If you want to sort this dictionary by values (i.e., the age), you must be another data structure such as a list, or an ordered dictionary.

### Use the sorted function and operator module

1 2 |
import operator sorted_d = sorted(d.items(), key=operator.itemgetter(1)) |

Sorted_d is a list of tuples sorted by the second element in each tuple. Each tuple contains the key and value for each item found in the dictionary. If you look at the content of this variable, you should get:

1 |
[ ('Zoe', 24), ('Anne', 33), ('Pierre', 42)] |

### Use the sorted function and lambda function

If you do not want to use the operator module, you can use a lambda function:

1 2 3 |
sorted_d = sorted(d.items(), key=lambda x: x[1]) # equivalent version # sorted_d = sorted(d.items(), key=lambda (k,v): v) |

The computation time is of the same order of magnitude as with the operator module. Would be interesting to test on large dictionaries.

### Use the sorted function and return an ordered dictionary

In the previous methods, the returned objects are list of tuples. So we do not have a dictionary anymore. You can use an OrderedDict if you prefer:

1 2 3 4 |
>>> from collections import OrderedDict >>> dd = OrderedDict(sorted(d.items(), key=lambda x: x[1])) >>> print(dd) OrderedDict([('Pierre', 24), ('Anne', 33), ('Zoe', 42)]) |

### Use sorted function and list comprehension

another method consists in using list comprehension and use the sorted function on the tuples made of (value, key).

1 |
sorted_d = sorted((value, key) for (key,value) in d.items()) |

Here the output is a list of tuples where each tuple contains the value and then the key:

1 |
[(24, 'Pierre'), (33, 'Anne'), (42, 'Zoe')] |

### Python 3.6 native sorting

In Python 3.6, the iteration through a dictionary is sorted. Consequently, you can just use:

1 |
sorted_d = [(k,v) for k,v in d.items()] |

The other advantage with this method is speed and the ability to return tuples as pairs of key/value or value/key.

### Benchmark

Here is a quick benchmark made using the small dictionary from the above examples. Would be interesting to redo the test with a large dictionary. This was done within a PYthon 3.6 environment.

What you can see is that the native Python dictionary sorting is pretty cool followed by the combination of the lambda + list comprehension method. Overall using one of these four methods would be equivalent though (factor 2/3 at most).

This image was created with the following code.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import operator import pylab from easydev import Timer times1, times2, times3, times4 = [], [], [], [] pylab.clf() d = {"Pierre": 42, "Anne": 33, "Zoe": 24} for j in range(20): N = 1000000 with Timer(times3): for i in range(N): sorted_d = sorted((key, value) for (key,value) in d.items()) with Timer(times2): for i in range(N): sorted_d = sorted(d.items(), key=lambda x: x[1]) with Timer(times1): for i in range(N): sorted_d = sorted(d.items(), key=operator.itemgetter(1)) with Timer(times4): for i in range(N): sorted_d = [(k,v) for k,v in d.items()] print(j) pylab.boxplot([times1, times2, times3, times4]) pylab.xticks([1,2,3,4], ["operator", "lambda", "list comprehension and lambda", "py36"]) pylab.ylabel("Time (seconds) 1 million sorting \n (repeated 20 times)") pylab.grid() pylab.title("Performance sorted dictionary by values") |