Effortlessly Sort Python Dict by Value
Sorting a Python Dictionary: Values, Keys, and More
by Ian Currie
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, you’ll learn how to sort dictionaries in Python.
Table of Contents
- Rediscovering Dictionary Order in Python
- Understanding What Sorting A Dictionary Really Means
- Sorting Dictionaries in Python
- Using the
sorted()
Function - Getting Keys, Values, or Both From a Dictionary
- Understanding How Python Sorts Tuples
- Using the
key
Parameter and Lambda Functions - Selecting a Nested Value With a Sort Key
- Converting Back to a Dictionary
- Using the
- Considering Strategic and Performance Issues
- Using Special Getter Functions to Increase Performance and Readability
- Measuring Performance When Using
itemgetter()
- Judging Whether You Want to Use a Sorted Dictionary
- Comparing the Performance of Different Data Structures
- Comparing the Performance of Sorting
- Comparing the Performance of Lookups
- Conclusion
Rediscovering Dictionary Order in Python
Before Python 3.6, dictionaries were inherently unordered. However, starting from Python 3.6, dictionaries started to conserve insertion order, and from Python 3.7, the insertion order has been guaranteed. This means that you can now rely on the order of elements in a dictionary.
Understanding What Sorting A Dictionary Really Means
When sorting a dictionary, it’s important to understand that the concept of sorting a dictionary by itself doesn’t make sense because dictionaries are inherently unordered data structures. However, you can extract the items from a dictionary and sort those.
Sorting Dictionaries in Python
Using the sorted()
Function
To sort a dictionary, you can use the sorted()
function and pass in the dictionary’s items as the argument. The sorted()
function will return a new list containing the sorted key-value pairs.
Output:
Getting Keys, Values, or Both From a Dictionary
If you only want to sort the keys or values of a dictionary, you can use the sorted()
function with the key
parameter.
To sort by keys:
Output:
To sort by values:
Output:
To sort by both keys and values:
Output:
Understanding How Python Sorts Tuples
When sorting a dictionary by its items, Python uses the natural order of the underlying data types. For example, it will sort strings alphabetically and integers numerically.
Using the key
Parameter and Lambda Functions
The key
parameter of the sorted()
function allows you to specify a custom sorting key. This is useful when you want to sort the items based on a specific attribute or nested value.
Output:
Selecting a Nested Value With a Sort Key
If you have a dictionary with nested values and you want to sort the items based on a nested attribute, you can use a lambda function to select the nested value.
Output:
Converting Back to a Dictionary
After sorting a dictionary, you might want to convert it back to a dictionary. You can do this by using a dictionary comprehension or the dict()
constructor.
Using a dictionary comprehension:
Output:
Using the dict()
constructor:
Output:
Considering Strategic and Performance Issues
When sorting dictionaries, there are some strategic and performance considerations to keep in mind.
Using Special Getter Functions to Increase Performance and Readability
If you’re sorting a large dictionary multiple times, you can use special getter functions like itemgetter()
to improve performance and readability.
Output:
Measuring Performance When Using itemgetter()
You can measure the performance of sorting a dictionary using itemgetter()
by using the timeit
module.
Output:
Judging Whether You Want to Use a Sorted Dictionary
While sorting dictionaries can be useful in some cases, it’s important to consider whether it’s the best option for your specific needs. Sorting a dictionary can take up extra memory and may not be necessary if you only need to access the key-value pairs in insertion order.
Comparing the Performance of Different Data Structures
If you’re working with large datasets and need to sort key-value data, you can also consider using alternative data structures like lists or pandas DataFrames. It’s worth comparing the performance of different data structures to find the most efficient solution for your problem.
Comparing the Performance of Sorting
In addition to comparing different data structures, you can also compare the performance of different sorting methods. This can help you determine the most efficient way to sort your key-value data.
Comparing the Performance of Lookups
When working with sorted dictionaries, it’s important to consider the performance of lookups. While sorting can be efficient, it may impact the performance of accessing specific key-value pairs.
Conclusion
Sorting dictionaries in Python can be done using the sorted()
function and specifying a sort key. It’s important to understand that dictionaries are inherently unordered, but you can extract the items and sort them based on specific criteria. By considering strategic and performance issues, you can determine whether using a sorted dictionary is the best option for your particular use case.