How To Sort A Python Dictionary

satyabrata pal
ML and Automation
Published in
2 min readSep 10, 2019

Well this will be a quick post and I will show three ways to sort a python dictionary, but none of these methods manipulates the original dictionary. Instead these are tricks to create a new dictionary where the values “look” like they are sorted because in the new dictionary the values are inserted in order which gives an impression that the original dictionary was sorted. Now let’s get to business.

Let’s consider the following dictionary which we will sort in three different ways.

unsorted_dictionary = {'inky':1, 'ponky':3, 'minky':2}

Sort by keys

We can use the python library method `sorted()`in combination with the dict() method to get a sorted dictionary. Here the original dictionary remains unaffected.

sorted_dictionary = dict(sorted(unsorted_dictionary.items()))
print(sorted_dictionary)
Output
------
{'inky': 1, 'minky': 2, 'ponky': 3}

Reverse the sort

Now we can use the reverse argument in the sorted() method to reverse the order of sorting done in previous section.

reverse_sorted_dictionary = dict(sorted(sorted_dictionary.items(), reverse = True))
print(reverse_sorted_dictionary)
Output
------
{'ponky': 3, 'minky': 2, 'inky': 1}

Sort by value

We can also use the sorted() method to sort the values as well as keys of the original dictionary and then zip the result before wrapping the zipped object in the dict() method to get a new dictionary which is sorted by value.

sorted_dict = dict(zip(sorted(reverse_sorted_dictionary.keys()),sorted(reverse_sorted_dictionary.values())))
print(sorted_dict)
Output
------
{'inky': 1, 'minky': 2, 'ponky': 3}

That’s how we can get an unsorted dictionary from an unsorted one. There are many more ways to sort a dictionary and much more efficient methods than what I have listed here. If you happen to know any other way to sort a dictionary then please post it in the comment section below.

The related code is available as a jupyter note book here.

--

--

satyabrata pal
ML and Automation

A QA engineer by profession, ML enthusiast by interest, Photography enthusiast by passion and Fitness freak by nature