Skip to content

Effortlessly Sort Python Dictionary by Value

[

Sorting a Python Dictionary: Values, Keys, and More

You’ve got a dictionary, but you’d like to sort the key-value pairs. Perhaps you’ve tried passing a dictionary to the sorted() function but haven’t gotten the results you expected. In this tutorial, we will go over everything you need to know if you want to sort dictionaries in Python.

Rediscovering Dictionary Order in Python

Before Python 3.6, dictionaries were inherently unordered. A Python dictionary is an implementation of the hash table, which is traditionally an unordered data structure.

As a side effect of the compact dictionary implementation in Python 3.6, dictionaries started to conserve insertion order. From Python 3.7, that insertion order has been guaranteed.

Understanding What Sorting A Dictionary Really Means

Sorting a dictionary means arranging its key-value pairs based on a specific criterion. This criterion can be the dictionary keys, values, or a combination of both.

Sorting Dictionaries in Python

Using the sorted() Function

The simplest way to sort a dictionary is by using the sorted() function. This function takes an iterable and returns a new list with the elements sorted in ascending order.

fruits = {
'apple': 3,
'banana': 2,
'orange': 4,
'mango': 1
}
sorted_fruits = sorted(fruits)
print(sorted_fruits)

Output:

['apple', 'banana', 'mango', 'orange']

Getting Keys, Values, or Both From a Dictionary

To sort a dictionary by its values, you can use the sorted() function with the key parameter and a lambda function.

fruits = {
'apple': 3,
'banana': 2,
'orange': 4,
'mango': 1
}
sorted_fruits_by_value = sorted(fruits.items(), key=lambda x: x[1])
print(sorted_fruits_by_value)

Output:

[('mango', 1), ('banana', 2), ('apple', 3), ('orange', 4)]

Understanding How Python Sorts Tuples

When sorting a dictionary by its values using the sorted() function, the key parameter accepts a lambda function that defines the sorting criterion. In this case, we are using a lambda function that takes each key-value pair as input and returns the second element of the pair (which is the value).

Using the key Parameter and Lambda Functions

To sort a dictionary by its keys, you can use the sorted() function with the key parameter and a lambda function.

fruits = {
'apple': 3,
'banana': 2,
'orange': 4,
'mango': 1
}
sorted_fruits_by_key = sorted(fruits.items(), key=lambda x: x[0])
print(sorted_fruits_by_key)

Output:

[('apple', 3), ('banana', 2), ('mango', 1), ('orange', 4)]

Selecting a Nested Value With a Sort Key

Sometimes, you may want to sort a dictionary based on a nested value. In this case, you can use a more complex lambda function to access the desired nested value.

fruits = {
'apple': {'quantity': 3},
'banana': {'quantity': 2},
'orange': {'quantity': 4},
'mango': {'quantity': 1}
}
sorted_fruits_by_nested_value = sorted(fruits.items(), key=lambda x: x[1]['quantity'])
print(sorted_fruits_by_nested_value)

Output:

[('mango', {'quantity': 1}), ('banana', {'quantity': 2}), ('apple', {'quantity': 3}), ('orange', {'quantity': 4})]

Converting Back to a Dictionary

If you want to convert the sorted list back into a dictionary, you can use the dict() constructor.

sorted_fruits_dict = dict(sorted_fruits_by_value)
print(sorted_fruits_dict)

Output:

{'mango': 1, 'banana': 2, 'apple': 3, 'orange': 4}

Considering Strategic and Performance Issues

Using Special Getter Functions to Increase Performance and Readability

When sorting a dictionary by its values using the sorted() function, you can improve performance and readability by using a special getter function instead of a lambda function.

from operator import itemgetter
fruits = {
'apple': 3,
'banana': 2,
'orange': 4,
'mango': 1
}
sorted_fruits_by_value = sorted(fruits.items(), key=itemgetter(1))
print(sorted_fruits_by_value)

Output:

[('mango', 1), ('banana', 2), ('apple', 3), ('orange', 4)]

Measuring Performance When Using itemgetter()

To measure the performance of sorting a dictionary by value using the itemgetter() function, you can use the timeit module.

from operator import itemgetter
import timeit
fruits = {
'apple': 3,
'banana': 2,
'orange': 4,
'mango': 1
}
sorted_fruits_by_value = sorted(fruits.items(), key=itemgetter(1))
execution_time = timeit.timeit(lambda: sorted(fruits.items(), key=itemgetter(1)), number=10000)
print(sorted_fruits_by_value)
print(f"Execution Time: {execution_time} seconds")

Output:

[('mango', 1), ('banana', 2), ('apple', 3), ('orange', 4)]
Execution Time: 0.1368275999999876 seconds

Judging Whether You Want to Use a Sorted Dictionary

Sorting a dictionary can be useful in certain scenarios, but it’s not a common pattern. Consider whether a sorted dictionary is really your best option before implementing it. There may be alternative data structures that better suit your needs.

Conclusion

In this tutorial, we covered various methods to sort a dictionary in Python. We learned how to use the sorted() function, how to get keys, values, or both from a dictionary, how Python sorts tuples, how to use the key parameter and lambda functions, how to select a nested value with a sort key, and how to convert back to a dictionary. We also discussed strategic and performance considerations when sorting dictionaries.