Skip to content

Sort Python Dictionary Explained with Examples Vijetha Spark By {Examples}

  • by

We can sort Python dictionaries by their keys or values using the sorted() function. Sorting is always a useful utility in everyday programming. Using the sorted() function we can sort the dictionary in ascending /descending order. This is a built-in function that is usually used to sort any iterable objects like lists, tuples, sets, and dictionaries.

In this article, I will explain how to sort a Python dictionary by its keys and values using the sorted() method in multiple ways with examples.

1. Quick Examples of Sorting Python Dictionary

Following are quick examples of how to sort dictionaries by their keys and values.

# Below are the quick examples

# Example 1: Sort the dictionary by keys
result = sorted(my_dict.items())
print(result)
# Convert to dictionary
new_dict = dict(result)

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

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

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

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

# Example 6: Sort the dictionary by values using sorted()
sorted_list = dict(sorted(my_dict.items(), key = lambda x:x[1]))

# Example 7: Sort the dictionary by values in descending order
sorted_list = dict(sorted(my_dict.items(), key = lambda x:x[1], reverse = True))

# Example 8: Update the existing dictionary with sorted values
sorted_list = sorted(my_dict.items(), key = lambda x:x[1]
my_dict.clear()
for key, value in sorted_list:
my_dict[key] = value

# Example 9: Sort the dictionary values
print(sorted(my_dict.values()))

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 Dictionary

3. Sort Python Dictionary

The sorted() function in Python is used to sort a dictionary by keys, 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.

# Sort the dictionary by keys
result = sorted(my_dict.items())
print(result)

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

Yields below output.

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 Python Dictionary in Descending Order

To sort the Python dictionary 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 keys 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 to Sort Elements

Alternatively, using dictionary comprehension we can sort the dictionary. 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 keys 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. Get a Sorted Key from the Dictionary

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 dictionary only keys using sorted()
print(sorted(my_dict))

# Output:
# [‘Apple’, ‘kiwi’, ‘papaya’, ‘pomegranate’, ‘strawberry’]

7. Sort Python Dictionary using Lambda Function

Let’s sort the dictionary using the lambda 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. Sort Python Dictionary by Values

Using the sorted() method we can sort the dictionary by values in Python. Pass the items() function as an iterable and key param(specify to sort by values using lambda function) into this function, it will sort the dictionary by values and finally, get the sorted dictionary by values using the dict() function.

# Sort the dictionary by values using sorted()
sorted_list = dict(sorted(my_dict.items(), key = lambda x:x[1]))
print(sorted_list)

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

9. Sort the Dictionary by Values in Descending Order

To sort the Python dictionary by value in descending order use the ‘reverse‘ param as ‘True‘ and then pass it into the sorted() function.

# Sort the dictionary by values in descending order
sorted_list = dict(sorted(my_dict.items(), key = lambda x:x[1], reverse = True))
print(sorted_list)

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

10. Update the Existing Dictionary with Sorted Values in Python

When we pass items() function and key param(specify to sort by value using lambda) into sorted() function, it will sort the given dictionary by value and return a sorted list of tuple key/value pairs. Before going to update the existing dictionary with sorted values we need to clear the existing dictionary using clear() method. Then using for loop iterate sorted_list for every iteration add key/value pair to the existing dictionary from the sorted list.

# Update the existing dictionary with sorted values
sorted_list = sorted(my_dict.items(), key = lambda x:x[1]
my_dict.clear()
for key, value in sorted_list:
my_dict[key] = value
print(my_dict)

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

11. Get Only Values After Sorting by Value

Let’s pass dict.values() function into sorted() function, it will return a list of all sorted values stored in the dictionary. For example,

# Sort the dictionary values
print(sorted(my_dict.values()))

# Output:
# [4, 5, 6, 10, 11]

12. Conclusion

In this article, I have explained the sorted() function and used this method along with items() to sort the dictionary by its keys and values in ascending/descending order with examples.

Happy learning!!

 We can sort Python dictionaries by their keys or values using the sorted() function. Sorting is always a useful utility in everyday programming. Using the sorted() function we can sort the dictionary in ascending /descending order. This is a built-in function that is usually used to sort any iterable objects like lists, tuples, sets, and  Read More Python, Python Tutorial, Python Dictionary Examples 

Leave a Reply

Your email address will not be published. Required fields are marked *