Skip to content

How to sort a dictionary by values in Python

Learn how you can sort a dictionary by values in Python.


Learn how you can sort a dictionary in Python.

By default, dictionaries preserve the insertion order since Python 3.7.

So the items are printed in the same order as they were inserted:

data = {"a": 4, "e": 1, "b": 99, "d": 0, "c": 3}

print(data)
# {'a': 4, 'e': 1, 'b': 99, 'd': 0, 'c': 3}

Sort a dictionary by values

To sort the dictionary by values, you can use the built-in sorted() function that is applied to dict.items(). Then you need to convert it back either with dictionary comprehension or simply with the dict() function:

sorted_data = {k: v for k, v in sorted(data.items(), key=lambda x: x[1])}

print(sorted_data)
# {'d': 0, 'e': 1, 'c': 3, 'a': 4, 'b': 99}

# Or

sorted_data = dict(sorted(data.items(), key=lambda x: x[1]))

print(sorted_data)
# {'d': 0, 'e': 1, 'c': 3, 'a': 4, 'b': 99}

Explanation: data.items() returns both the keys and the values as tuple. Then, sorted() sorts the pairs, and the key argument is applied with a function returning x[1]. This refers to the second item in the tuple, hence the value. So all items are sorted according to the value.

And sorted() returns a list of tuples:

print(sorted(data.items(), key=lambda x: x[1]))
# [('d', 0), ('e', 1), ('c', 3), ('a', 4), ('b', 99)]

So it needs to be converted back to a dictionary in the end.


FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*


PySaaS: The Pure Python SaaS Starter Kit

🚀 Build a software business faster with pure Python: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏