Kodeclik Blog
About
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.
Popular Classes
Scratch Coding
Minecraft Coding
TinkerCAD
Roblox Studio
Python for Kids
Javascript for Kids
Pre-Algebra
Geometry for Kids
Copyright @ Kodeclik 2024. All rights reserved.
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:
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:
This will produce the output:
You can also print the dictionary using:
This will produce the following structure:
If you would like just the keys (ie the month values), you do:
which will give:
Similarly, the values can be obtained using:
with the corresponding output:
So how do we sort the Python dictionary by keys? Here the keys are the month names.
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:
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:
Note that “April” is the first month and “September” is the last month (in alphabetical order).
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:
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:
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.
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
}
print(days_in_months)
{'January': 31, 'February': 28, 'March': 31,
'April': 30, 'May': 31, 'June': 30, 'July': 31,
'August': 31, 'September': 30, 'October': 31,
'November': 30, 'December': 31}
print(days_in_months.items())
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)])
print(days_in_months.keys())
dict_keys(['January', 'February', 'March',
'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'])
print(days_in_months.values())
dict_values([31, 28, 31, 30, 31, 30, 31,
31, 30, 31, 30, 31])
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)
{'April': 30, 'August': 31, 'December': 31,
'February': 28, 'January': 31, 'July': 31,
'June': 30, 'March': 31, 'May': 31,
'November': 30, 'October': 31, 'September': 30}
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)
{'April': 30, 'August': 31, 'December': 31,
'February': 28, 'January': 31, 'July': 31,
'June': 30, 'March': 31, 'May': 31,
'November': 30, 'October': 31, 'September': 30}