You can sort a dictionary in python by using the sorted() function. it is actually possible to do a “sort by dictionary values”.
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.
Python sort dictionary by value Example
Python 3.6+
1. sort dictionary by value Ascending
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)]
2. Sort dictionary by value descending
Just use reverse=True
in the sorted() function.
d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4} a = sorted(d.items(), key=lambda x: x[1], reverse=True) print(a)
Output:
[(‘five’, 5), (‘four’, 4), (‘three’, 3), (‘two’, 2), (‘one’, 1)]
Older Python
import operator
import operator x = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4} sorted_x = sorted(x.items(), key=operator.itemgetter(1)) print(sorted_x)
sorted_x
will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x
.
And for those sort dictionary by key python instead of values:
import operator x = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4} sorted_x = sorted(x.items(), key=operator.itemgetter(0)) print(sorted_x)
Output:
[(‘five’, 5), (‘four’, 4), (‘one’, 1), (‘three’, 3), (‘two’, 2)]
How to sort a dictionary by key python 3
Standard Python dictionaries are unordered. Even if you sorted the (key,value) pairs, you wouldn’t be able to store them in a dict
in a way that would preserve the ordering.
The easiest way is to use OrderedDict, which remembers the order in which the elements have been inserted:
import collections d = {2: 3, 1: 89, 4: 5, 3: 0} od = collections.OrderedDict(sorted(d.items())) print(od)
Output:
OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
Python 3
For Python 3 users, one needs to use the .items()
instead of .iteritems()
:
import collections d = {2: 3, 1: 89, 4: 5, 3: 0} od = collections.OrderedDict(sorted(d.items())) for k, v in od.items(): print(k, v)
Output:
1 89
2 3
3 0
4 5
Python sort dictionary by value than key
The key=lambda x: (x[1],x[0])
tells sorted
that for each item x
in y.items()
, use (x[1],x[0])
as the proxy value to be sorted. Since x
is of the form (key,value)
, (x[1],x[0])
yields (value,key)
. This causes sorted
to sort by value
first, then by key
for tie-breakers.
reverse=True
tells sorted
to present the result in descending, rather than ascending order.
y = {100: 1, 90: 4, 99: 3, 92: 1, 101: 1} n = sorted(y.items(), key=lambda x: (x[1], x[0]), reverse=True) print(n)
Output: [(90, 4), (99, 3), (101, 1), (100, 1), (92, 1)]
Do comment if you have any doubts and suggestions on this tutorial.
Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.