Python Sort Dictionary by Key

We can sort the dictionary by key using a sorted() function in Python. It can be used to sort dictionaries by key in ascending order or descending order. When we pass the dictionary into the sorted() function by default it sorts the keys of the dictionary and returns them as a list.

This function sorts iterable objects like lists, tuples, sets, and dictionaries. In this article, I will explain how to sort a dictionary by key in ascending/descending order using Pyhton sorted() function.

1. Quick Examples of Sort Dictionary by Key in Python

Following are quick examples of sorting dictionaries by key.


# Below are the quick examples

# Example 1: Sort the dictionary by key in ascending order 
new_dict = dict(sorted(my_dict.items())) 

# Example 2: Sort the dictionary by key in descending order
new_dict = dict(sorted(my_dict.items(),  reverse = True)) 

# Example 3: Sort the dictionary by key using dict comprehension
Keys = list(my_dict.keys())
Keys.sort()
new_dict = {key: my_dict[key] for key in Keys}

# Example 4: Sort only keys using sorted()
print(sorted(my_dict))

# Example 5: Sort the dictionary by keys using items()
new_dict = dict(sorted(my_dict.items(), key=lambda item: item[0]))

2. What is Python Dictionary

A Python dictionary is a collection that is unordered, mutable, and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with {} and key: value pair separated by commas. The dictionaries are indexed by keys.

Let’s create a Python dictionary where, the 'keys' are 'string' type and 'values' are 'int' type.


# Create dictionary
my_dict = {'Apple':5, 'papaya':6, 'kiwi':4, 'pomegranate':11, 'strawberry':10}
print(my_dict)
print(type(my_dict))

Yields below output.

python Sort Dictionary key
Python Dictionary

3. Sort Python Dictionary by Key in Ascending Order

The sorted() function in Python is used to sort a dictionary by key, By default, this function takes the dictionary as input, sorts the keys in dict, and returns only keys as a list in sorted order.

If we want to get the sorted dictionary by keys in the form of the dictionary, we should use dictionary items() as input to the sorted() function. This returns the list of tuples with the sorted values and use this result in dict() function to get the dictionary where the key-value pairs are in ascending order.


# Create dictionary
my_dict = {'Apple':5, 'papaya':6, 'kiwi':4, 'pomegranate':11, 'strawberry':10}
print(my_dict)
print(type(my_dict))

# Sort the dictionary by key in ascending order 
result = sorted(my_dict.items())
print(result)

# Convert to dictionary
new_dict = dict(result)
print(new_dict)

Yields below output.

python sort dictionary keys
Sorted Python Dictionary

Explanation:

  • The items() method returns dictionary elements as tuples in a list.
  • sorted() function sorts the list of tuples.
  • dict() convert the sorted list of tuples back to a dictionary.

4. Sort Dictionary by key in Descending Order

To sort the Python dictionary by key in descending order use the ‘reverse‘ param as ‘True‘ and then pass it into the sorted() function. I have a dedicated article on sorting in reverse order in Python.


# Sort the dictionary by key in descending order
new_dict = dict(sorted(my_dict.items(),  reverse = True))
print(new_dict)

# Output: 
{'strawberry': 10, 'pomegranate': 11, 'papaya': 6, 'kiwi': 4, 'Apple': 5}

Explanation:

  • The items() method returns dictionary elements as tuples in a list.
  • sorted() function sorts the list of tuples.
  • reverse = True param to sorted() sort the values in descending order.
  • dict() convert the sorted list of tuples back to a dictionary.

5. Using Dictionary Comprehension Sort by Key

Alternatively, using dictionary comprehension we can sort the dictionary by key. In order to sort the dictionary using comprehension first, we have to sort the list of keys from the dictionary using the list.sort() function and iterate the list using for loop, for each iteration add a new sorted key to the new dictionary in a comprehension.


# Sort the dictionary by key using dict comprehension
Keys = list(my_dict.keys())
Keys.sort()
new_dict = {key: my_dict[key] for key in Keys}
print(new_dict)

# Output:
# {'Apple': 5, 'kiwi': 4, 'papaya': 6, 'pomegranate': 11, 'strawberry': 10}

6. Sort Only Dictionary Keys using sorted()

When we pass the Python dictionary into sorted() function by default it will sort the keys of the dictionary and returns only keys. Note that the returned list contains only the sorted keys.


# Sort only keys using sorted()
print(sorted(my_dict))

# Output:
# ['Apple', 'kiwi', 'papaya', 'pomegranate', 'strawberry']

7. Sort Python Dictionary by Keys using items()

We can also sort the dictionary by keys using the items() function along with the lambda function. Pass the items() function and lambda function into the sorted() function, it will sort the dictionary by keys and finally, get the sorted dictionary by keys using the dict() function.


# Sort the dictionary by keys using items()
new_dict = dict(sorted(my_dict.items(), key=lambda item: item[0]))
print(new_dict)

# Output:
# {'Apple': 5, 'kiwi': 4, 'papaya': 6, 'pomegranate': 11, 'strawberry': 10}

8. Conclusion

In this article, I have explained how to sort a dictionary by key in ascending/descending order using Pyhton sorted() function. And also explained using dictionary comprehension and items() function to sort the dictionary by keys with examples.

Leave a Reply

You are currently viewing Python Sort Dictionary by Key