How to Sort a Dictionary by Key in Python
In this tutorial, we are going to see how to sort a dictionary by key in Python. A dictionary in Python is a very versatile and useful type of container, capable of storing a collection of values and retrieving them via keys.
Values can be objects of any type (dictionaries can even be nested within other dictionaries) and keys can be of any object as long as it’s hashable, which means it’s immutable. Unlike lists or tuples, key/value pairs in dictionaries don’t have a defined order, which means we can have a dictionary like this:
colors = {'blue': 2, 'red': 1, 'green': 4, 'orange': 3}
How to Sort a Dictionary by Key in Python
If we want to sort objects in a dictionary according to their keys, the easiest way is to use Python’s “sorted” method, which takes any iterable and returns a list of sorted values (in ascending order by default).
names = {'carlos': 2, 'daoud': 1, 'bob': 4, 'alex': 3} for k in sorted(names.keys()): print("%s: %s" % (k, names[k]))
Output:
alex: 3 bob: 4 carlos: 2 daoud: 1
We notice that this method returned a list of keys in ascending order, and almost in alphabetical order.