python - How do I sort a dictionary by value?

ID : 144

viewed : 296

Tags : pythonsortingdictionarypython





Top 5 Answer for python - How do I sort a dictionary by value?

vote vote

91

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[1])} {0: 0, 2: 1, 1: 2, 4: 3, 3: 4} 

or

>>> dict(sorted(x.items(), key=lambda item: item[1])) {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[1]) 

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

import collections  sorted_dict = collections.OrderedDict(sorted_x) 
vote vote

83

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.

vote vote

71

You could use:

sorted(d.items(), key=lambda x: x[1]) 

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[1], reverse=True) 

Input:

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

Output:

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

66

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

57

In recent Python 2.7, we have the new OrderedDict type, which remembers the order in which the items were added.

>>> d = {"third": 3, "first": 1, "fourth": 4, "second": 2}  >>> for k, v in d.items(): ...     print "%s: %s" % (k, v) ... second: 2 fourth: 4 third: 3 first: 1  >>> d {'second': 2, 'fourth': 4, 'third': 3, 'first': 1} 

To make a new ordered dictionary from the original, sorting by the values:

>>> from collections import OrderedDict >>> d_sorted_by_value = OrderedDict(sorted(d.items(), key=lambda x: x[1])) 

The OrderedDict behaves like a normal dict:

>>> for k, v in d_sorted_by_value.items(): ...     print "%s: %s" % (k, v) ... first: 1 second: 2 third: 3 fourth: 4  >>> d_sorted_by_value OrderedDict([('first': 1), ('second': 2), ('third': 3), ('fourth': 4)]) 

Top 3 video Explaining python - How do I sort a dictionary by value?







Related QUESTION?