# How do I sort a dictionary by value? – Dev

The best answers to the question “How do I sort a dictionary by value?” in the category Dev.

QUESTION:

I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.

I can sort on the keys, but how can I sort based on the values?

Note: I have read Stack Overflow question here How do I sort a list of dictionaries by a value of the dictionary? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution to sort either in ascending or descending order.

## As simple as: `sorted(dict1, key=dict1.get)`

Well, it is actually possible to do a “sort by dictionary values”. Recently I had to do that in a Code Golf (Stack Overflow question Code golf: Word frequency chart). Abridged, the problem was of the kind: given a text, count how often each word is encountered and display a list of the top words, sorted by decreasing frequency.

If you construct a dictionary with the words as keys and the number of occurrences of each word as value, simplified here as:

``````from collections import defaultdict
d = defaultdict(int)
for w in text.split():
d[w] += 1
``````

then you can get a list of the words, ordered by frequency of use with `sorted(d, key=d.get)` – the sort iterates over the dictionary keys, using the number of word occurrences as a sort key .

``````for w in sorted(d, key=d.get, reverse=True):
print(w, d[w])
``````

I am writing this detailed explanation to illustrate what people often mean by “I can easily sort a dictionary by key, but how do I sort by value” – and I think the original post was trying to address such an issue. And the solution is to do sort of list of the keys, based on the values, as shown above.

### Python 3.7+ or CPython 3.6

Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it’s an implementation detail.

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

or

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

### Older Python

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

For instance,

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

`sorted_x` will be a list of tuples sorted by the second element in each tuple. `dict(sorted_x) == x`.

And for those wishing to sort on keys instead of values:

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

In Python3 since unpacking is not allowed we can use

``````x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv)
``````

If you want the output as a dict, you can use `collections.OrderedDict`:

``````import collections

sorted_dict = collections.OrderedDict(sorted_x)
``````

Dicts can’t be sorted, but you can build a sorted list from them.

A sorted list of dict values:

``````sorted(d.values())
``````

A list of (key, value) pairs, sorted by value:

``````from operator import itemgetter
sorted(d.items(), key=itemgetter(1))
``````

You could use:

``````sorted(d.items(), key=lambda x: x)
``````

This will sort the dictionary by the values of each entry within the dictionary from smallest to largest.

To sort it in descending order just add `reverse=True`:

``````sorted(d.items(), key=lambda x: x, reverse=True)
``````

Input:

``````d = {'one':1,'three':3,'five':5,'two':2,'four':4}
a = sorted(d.items(), key=lambda x: x)
print(a)
``````

Output:

``````[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]
``````