This post will discuss how to iterate over a dictionary in sorted order of its keys or values in Python.

With Python 3.7, a dictionary is guaranteed to be iterated in the insertion order of keys. If you need to iterate over a dictionary in sorted order of its keys or values, you can pass the dictionary’s entries to the sorted() function, which returns a list of tuples. You can get the view on the dictionary’s entries using either dict.items() or dict.keys() function.

1. Using dict.items() function

A standard solution to iterate over a dictionary in sorted order of keys is using the dict.items() with sorted() function.

Download  Run Code

 
To iterate in reverse order of keys, you can specify the reverse argument of the sorted() function as True.

Download  Run Code

2. Using dict.keys() function

Another simple solution to iterate over a dictionary in the sorted order of keys is to use the dict.keys() with the sorted() function.

Download  Run Code

 
This is equivalent to:

Download  Run Code

 
Alternatively, to iterate in reverse order of keys, you can specify the reverse argument of the sorted() function as True.

Download  Run Code

 
Finally, to iterate the dictionary in sorted order of values, you can supply the key argument of the sorted() function.

Download  Run Code

 
If the dictionary’s values are numeric, you can also use the Counter class from the collections module to iterate over the dictionary in decreasing order of their values.

Download  Run Code

That’s all about iterating over a dictionary in sorted order in Python.