Sorting Dictionary by Key in Python

Table of Contents

This python program sorts dictionary on the basis of key in ascending and descending order.

Dictionary is very useful built-in data types in python. Dictionary is an unordered collection of items and has a key-value pair.

While programming, it is often require to sort dictionary data either in ascending or descending order based on key or value. In this programming examples, we sort dictionary data on the basis of key.

To sort dictionary in python, lamda function is very handy. In this example, we use lambda function to sort a dictionary by key.

Consider we have following dictionary:


# Dictionary for item and price
# item as key & price as value
data = {'banana': 80,'cherry': 200,'apple': 60,'grapes':120}

And, we want to sort this dictionary by key (fruits) name in alphabetical order.

Sorting Dictionary by Key in Ascending Order


# Dictionary for item and price
# item as key & price as value
data = {'banana': 80,'cherry': 200,'apple': 60,'grapes':120}

# Sorting on the basis of key in alphabetically ascending order
sorted_result = sorted(data.items())

print(sorted_result)

Output

[('apple', 60), ('banana', 80), ('cherry', 200), ('grapes', 120)]

Sorting Dictionary by Key in Descending Order


# Dictionary for item and price
# item as key & price as value
data = {'banana': 80,'cherry': 200,'apple': 60,'grapes':120}

# Sorting on the basis of key in alphabetically descending order
sorted_result = sorted(data.items(), reverse=True)

print(sorted_result)

Output

[('grapes', 120), ('cherry', 200), ('banana', 80), ('apple', 60)]