Easy way to sort a dictionary by key and value Python

onestop_databy:

Python

Do you know how to sort a dictionary by value in Python? This is one of those uncommon dictionary operations that sometimes you need to do and don’t remember how to. This tutorial teaches how to do it and how to sort a dictionary by value in Python.

1. How to Sort a Dictionary by Key in Python

First and foremost, in Python 3.7 it was introduced a feature to Python that the order of the elements in the data structure is the same as it is inputted. This was not true for the previous Python versions — which used an order based on a hash function.

However, not always the input order is the sorted order of elements. In Python 3.7 and above, sorted() can be used to sort the dictionary keys and can be used to re-generating a new (sorted) dict – see below:

my_dict = {
    "zebra": "animal",
    "pen": "object",
    "wordpress": "CMS"
}

# print elements in dict
>>> for elem in my_dict:
>>>    print(elem, my_dict[elem])

# we see that the order of the elements are the same as entered

>>> zebra animal
>>> pen object
>>> wordpress CMS

Now, sorting the dict by key can be done using sorted()

# print elements in dict
>>> for elem in sorted(my_dict):
>>>    print(elem, my_dict[elem])

# we see that the sorting by key works!
>>> pen object
>>> wordpress CMS
>>> zebra animal

Moreover, sometimes the descending is desired, just pass “reverse=True” in sorted().

2. How to Sort a Dictionary by Value in Python

Last but not least, a dictionary can also be sorted by values — less common:

# define dict
my_dict = {
    "zebra": "animal",
    "pen": "object",
    "wordpress": "CMS"
}

# sort by value
my_dict = sorted(my_dict.items(), key=lambda x: x[1])

# print sorted dict
>>> for key, value in my_dict:
>>>    print(key, value)

# sorted values
>>> wordpress CMS
>>> zebra animal
>>> pen object

Last but not least, if the descending is wanted, just pass “reverse=True” in sorted().

Related Posts