How to Sort Dictionaries by Key or Value in Python

09/13/2021

Contents

In this article, you will learn how to sort sictionaries by key or value in Python.

How to Sort Dictionaries by Key or Value

In Python, dictionaries are unordered collections of key-value pairs. However, you can sort dictionaries based on their keys or values by using the built-in sorted() function or the sorted() method of dictionary objects.

Sorting by Key

To sort a dictionary by key, you can pass the keys() method of the dictionary as an argument to the sorted() function. This will return a sorted list of the dictionary keys. You can then iterate over this list to access the dictionary values in the sorted order.

my_dict = {'a': 5, 'c': 2, 'b': 3}
sorted_keys = sorted(my_dict.keys())
for key in sorted_keys:
    print(key, my_dict[key])

# Output:
a 5
b 3
c 2

Sorting by Value

To sort a dictionary by value, you can pass the items() method of the dictionary as an argument to the sorted() function. This will return a sorted list of the dictionary key-value pairs based on the values. You can then iterate over this list to access the sorted key-value pairs.

my_dict = {'a': 5, 'c': 2, 'b': 3}
sorted_items = sorted(my_dict.items(), key=lambda x: x[1])
for key, value in sorted_items:
    print(key, value)

# Output:
c 2
b 3
a 5

In the key parameter of the sorted() function, we pass a lambda function that returns the second element of the tuple, which represents the value of the dictionary key-value pair. This tells the sorted() function to sort the dictionary based on the values.