Kodeclik Blog
How to sort a Python dictionary by key
To understand how to sort a Python dictionary by key, let us recap some basic ways in which a Python dictionary works.
A Python dictionary is a collection of key-value pairs where each key is unique. It is an unordered, mutable data structure. Here's an example of a Python dictionary with month names as keys and the number of days in each month as values:
days_in_months = {
"January": 31,
"February": 28, # 29 in a leap year
"March": 31,
"April": 30,
"May": 31,
"June": 30,
"July": 31,
"August": 31,
"September": 30,
"October": 31,
"November": 30,
"December": 31
}
In the code above, days_in_months is a dictionary where the month names are the keys and the number of days in each month are the values. This dictionary allows you to retrieve the number of days in a month by using the month name as the key.
People also call dictionaries as “associative arrays”, as they associate values with keys.
The provided dictionary can be used for various purposes such as determining the number of days in a specific month, performing calculations based on the number of days in different months, or generating reports based on the number of days in each month.
Once you have a dictionary, you can do the following operations on it.
You can print the dictionary like so:
print(days_in_months)
This will produce the output:
{'January': 31, 'February': 28, 'March': 31,
'April': 30, 'May': 31, 'June': 30, 'July': 31,
'August': 31, 'September': 30, 'October': 31,
'November': 30, 'December': 31}
You can also print the dictionary using:
print(days_in_months.items())
This will produce the following structure:
dict_items([('January', 31), ('February', 28),
('March', 31), ('April', 30), ('May', 31),
('June', 30), ('July', 31), ('August', 31),
('September', 30), ('October', 31), ('November', 30),
('December', 31)])
If you would like just the keys (ie the month values), you do:
print(days_in_months.keys())
which will give:
dict_keys(['January', 'February', 'March',
'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'])
Similarly, the values can be obtained using:
print(days_in_months.values())
with the corresponding output:
dict_values([31, 28, 31, 30, 31, 30, 31,
31, 30, 31, 30, 31])
So how do we sort the Python dictionary by keys? Here the keys are the month names.
Method 1: Sorting a Python dictionary using sorted()
To sort a Python dictionary by its keys, we use the built-in sorted function along with the items method of the dictionary. Here's the code to achieve this:
days_in_months = {
"January": 31,
"February": 28, # 29 in a leap year
"March": 31,
"April": 30,
"May": 31,
"June": 30,
"July": 31,
"August": 31,
"September": 30,
"October": 31,
"November": 30,
"December": 31
}
sorted_calendar = dict(sorted(days_in_months.items()))
print(sorted_calendar)
Note that we gave the items() as input to the sorted function which presents the input as pairs of month, day values. When sorted() is applied on it, it sorts the pairs in terms of the key (i.e., month). The result is used by the dict() constructor to create a new dictionary called sorted_calendar.
The output will be:
{'April': 30, 'August': 31, 'December': 31,
'February': 28, 'January': 31, 'July': 31,
'June': 30, 'March': 31, 'May': 31,
'November': 30, 'October': 31, 'September': 30}
Note that “April” is the first month and “September” is the last month (in alphabetical order).
Method 2: Sorting a Python dictionary using keys()
Recall that keys() will return just the keys of the dictionary. So we can retrieve the keys, sort just the keys, and then index back into the dictionary to retrieve the entries in the order we desire. Here is some code that works along these lines:
days_in_months = {
"January": 31,
"February": 28, # 29 in a leap year
"March": 31,
"April": 30,
"May": 31,
"June": 30,
"July": 31,
"August": 31,
"September": 30,
"October": 31,
"November": 30,
"December": 31
}
months = list(days_in_months.keys())
months.sort()
sorted_calendar = {x: days_in_months[x] for x in months}
print(sorted_calendar)
In the above code, after creating a dictionary as before called "days_in_months" that maps each month to the number of days in that month, we create a list of the keys (months) from the "days_in_months" dictionary, sorts this list, and finally create a new dictionary called "sorted_calendar" by iterating over the sorted list of months and adding the corresponding key-value pairs from the "days_in_months" dictionary. The code then prints the "sorted_calendar" dictionary.
The output will be as before:
{'April': 30, 'August': 31, 'December': 31,
'February': 28, 'January': 31, 'July': 31,
'June': 30, 'March': 31, 'May': 31,
'November': 30, 'October': 31, 'September': 30}
So we have seen two methods to sort a dictionary by key. In one we use sorted() directly on the dictionary and it sorts by keys. In the other, we create a list of keys and then sort this list to index back into the dictionary. The second approach is more verbose but clearer on what it does. The first approach is more succinct. Which one is your favorite?
Sorting a calendar is not the only example of when you will need to sort a Python dictionary. Another real-life example of sorting a Python dictionary by key is when you are dealing with say a dictionary of student names and their corresponding test scores. For instance, if you have a dictionary where the keys are student names and the values are their test scores, sorting the dictionary by keys (student names) is useful in providing an alphabetical view.
Want to learn Python with us? Sign up for 1:1 or small group classes.