W3docs

How do I sort a dictionary by key?

In Python, dictionaries are unordered collections of key-value pairs.

In Python, dictionaries are unordered collections of key-value pairs. However, you can sort the keys of a dictionary and use them to iterate over the dictionary in a specific order.

Here's an example of how you can sort the keys of a dictionary and iterate over the key-value pairs in sorted order:

Sort a dictionary by keys in Python by sorting the keys array

python— editable, runs on the server

This will output:


a 1
b 2
c 3

Alternatively, you can use the items() method of the dictionary along with the sorted() function, like so:

Sort a dictionary by keys in Python by sorting the items array

python— editable, runs on the server

This will give you the same output as previous example.

If you want to sort the dictionary by the values instead, you can pass a key function to the sorted() function that retrieves the values from the tuple returned by items(). You can also reverse the sorting order by passing reverse=True as an argument to the sorted() function.

Sort a dictionary by values in Python

python— editable, runs on the server

This will output:


a 1
b 2
c 3

Additionally, python 3.7 and above you can use the dict() constructor and pass an ordered dict, to create a dict sorted by key

Sort a dictionary by in Python 3.7 or above using the dict constructor

python— editable, runs on the server

This will output:


{'a': 1, 'b': 2, 'c': 3}

Keep in mind that creating a new dictionary object means that the original dictionary is not modified.