Python sort dictionary by Value/Key | Ascending & Descending order examples

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

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.

Output:

[(‘five’, 5), (‘four’, 4), (‘three’, 3), (‘two’, 2), (‘one’, 1)]

Older Python

import operator

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:

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:

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():

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.

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.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.