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 go over everything you need to know if you want to sort dictionaries in Python.
In this tutorial, you’ll:
- Review how to use the
sorted()
function - Learn how to get dictionary views to iterate over
- Understand how dictionaries are cast to lists during sorting
- Learn how to specify a sort key to sort a dictionary by value, key, or nested attribute
- Review dictionary comprehensions and the
dict()
constructor to rebuild your dictionaries - Consider alternative data structures for your key-value data
Along the way, you’ll also use the timeit
module to time your code and get tangible results for comparing the different methods of sorting key-value data. You’ll also consider whether a sorted dictionary is really your best option, as it’s not a particularly common pattern.
To get the most out of this tutorial, you should know about dictionaries, lists, tuples, and functions. With that knowledge, you’ll be able to sort dictionaries by the end of this tutorial. Some exposure to higher-order functions, such as lambda functions, will also come in handy but isn’t a requirement.
Free Download:Click here to download the code that you’ll use to sort key-value pairs in this tutorial.
First up, you’ll learn some foundational knowledge before trying to sort a dictionary 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 3.7, that insertion order has been guaranteed.
If you wanted to keep an ordered dictionary as a data structure before compact dictionaries, then you could use OrderedDict
from the collections
module. Similar to the modern compact dictionary, it also keeps insertion order, but neither type of dictionary sorts itself.
Another alternative for storing an ordered key-value pair data is to store the pairs as a list of tuples. As you’ll see later in the tutorial, using a list of tuples could be the best choice for your data.
An essential point to understand when sorting dictionaries is that even though they conserve insertion order, they’re not considered a sequence. A dictionary is like a set of key-value pairs, and sets are unordered.
Dictionaries also don’t have much reordering functionality. They’re not like lists, where you can insert elements at any position. In the next section, you’ll explore the consequences of this limitation further.
Understanding What Sorting A Dictionary Really Means
Because dictionaries don’t have much reordering functionality, when sorting a dictionary, it’s rarely done in-place. In fact, there are no methods for explicitly moving items in a dictionary.
If you wanted to sort a dictionary in-place, then you’d have to use the del
keyword to delete an item from the dictionary and then add it again. Deleting and then adding again effectively moves the key-value pair to the end.
The OrderedDict
class has a specific method to move an item to the end or the start, which may make OrderedDict
preferable for keeping a sorted dictionary. However, it’s still not very common and isn’t very performant, to say the least.
The typical method for sorting dictionaries is to get a dictionary view, sort it, and then cast the resulting list back into a dictionary. So you effectively go from a dictionary to a list and back into a dictionary. Depending on your use case, you may not need to convert the list back into a dictionary.
Note: Sorted dictionaries aren’t a very common pattern. You’ll explore more about that topic later in the tutorial.
With those preliminaries out of the way, you’ll get to sorting dictionaries in the next section.
Sorting Dictionaries in Python
In this section, you’ll be putting together the components of sorting a dictionary so that, in the end, you can master the most common way of sorting a dictionary:
>>> people={3:"Jim",2:"Jack",4:"Jane",1:"Jill"}>>> # Sort by key>>> dict(sorted(people.items())){1: 'Jill', 2: 'Jack', 3: 'Jim', 4: 'Jane'}>>> # Sort by value>>> dict(sorted(people.items(),key=lambdaitem:item[1])){2: 'Jack', 4: 'Jane', 1: 'Jill', 3: 'Jim'}
Don’t worry if you don’t understand the snippets above—you’ll review it all step-by-step in the following sections. Along the way, you’ll learn how to use the sorted()
function with sort keys, lambda
functions, and dictionary constructors.
Read the full article at https://realpython.com/sort-python-dictionary/ »
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]