You are currently viewing 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.

Advertisements

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

If you are in a hurry, below are some quick examples of sorting dictionaries by key in Python.


# Quick examples of sort dictionary by key

# 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 keys
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}

Frequently Asked Questions On Python Sort Dictionary by Key

How can I sort a dictionary in Python by its keys?

To sort a dictionary in Python by its keys, you can use the sorted() function along with dictionary comprehension. For example, sorted(my_dict) returns a sorted list of keys, and then a new dictionary is created using a dictionary comprehension that iterates over the sorted keys.

Can I sort a dictionary in descending order by keys?

You can sort a dictionary in descending order by using the reverse=True parameter with the sorted() function.

Is there an alternative method to sort a dictionary by keys?

There’s an alternative method to sort a dictionary by keys using the items() method along with the sorted() function. This approach allows you to work directly with key-value pairs.

How does the sorting process work for dictionary keys?

The sorted() function sorts the keys of the dictionary by default. The sorting is done based on the natural order of the keys (alphabetical or numerical) unless a custom sorting function is provided.

Can I sort a dictionary with a custom sorting function for keys?

You can sort a dictionary with a custom sorting function for keys by using the key parameter of the sorted() function. The key parameter allows you to specify a custom function to determine the sort order.

Will sorting a dictionary modify the original dictionary?

Sorting a dictionary using the methods mentioned earlier, whether using dictionary comprehension or the items() method with sorted(), will not modify the original dictionary. Both approaches create a new dictionary or list with the sorted order.

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.

Related Articles

References