To sort a dictionary by key in Python, use the dictionary comprehension expression {key:dict[key] for key in sorted(
to create a new dictionary with keys in sorted order. You iterate over all keys in sorted order, obtain their associated values with dict
)}rank[key]
, and put them into a new dictionary. Python dictionaries preserve the order—even if the specification doesn’t require this because dictionaries are unordered data structures.
Problem: Given a dictionary; how to sort it by keys?
Example: The following example shows a dictionary by the name rank
that stores the names of individuals as the keys while their corresponding ranks represent the values. We’ll use this example as a reference while discussing the solutions.
rank = { 'Bob': 2, 'Alice': 4, 'Sharon': 5, 'Dwyane': 1, 'John': 3 } # Some Procedure to Sort the Dictionary by its Keys
Output: Here’s your desired output.
{'Alice': 4, 'Bob': 2, 'Dwyane': 1, 'John': 3, 'Sharon': 5}
Method 1: Sort a Dictionary by Key and Return a List of Keys
Solution 1: If you’re just interested in the keys, you can use the sorted(dict)
function to create a sorted list of dictionary keys.
rank = { 'Bob': 2, 'Alice': 4, 'Sharon': 5, 'Dwyane': 1, 'John': 3 } sorted_ranks = sorted(rank) print(sorted_ranks) # ['Alice', 'Bob', 'Dwyane', 'John', 'Sharon']
Method 2: Sort a Dictionary by Key and Return an Ordered Dictionary
Solution 2: If you actually want to obtain a sorted dictionary, you can use dictionary comprehension.
rank = { 'Bob': 2, 'Alice': 4, 'Sharon': 5, 'Dwyane': 1, 'John': 3 } sorted_ranks = {key:rank[key] for key in sorted(rank)} print(sorted_ranks) # {'Alice': 4, 'Bob': 2, 'Dwyane': 1, 'John': 3, 'Sharon': 5}
You iterate over all keys in sorted order, obtain their associated values with rank[key]
, and put them into a new dictionary. As of today, Python dictionaries still preserve the order—even if they don’t have to from a specification point of view because, technically, dictionaries are unordered data structures.
You’ve now learned how to sort a dictionary by key. But how to sort it by value? Let’s find out!
Video — How to Sort a Dictionary by Value in Python?
Read More: You can check out our full article for multiple methods on sorting a dictionary (by value) in Python.
Interactive Puzzle — Sort a Dictionary Application
# mg per 100g omega3_table = { "Salmon" : 2260, "Hering" : 1729, "Sardines" : 1480, "Flaxseeds" : 53400, "Eggs" : 400 } y = sorted(omega3_table, key=lambda x : omega3_table[x]) print(y[-1])
Puzzle: What is the output of this puzzle?
You can solve the puzzle in our interactive Finxter app in your browser:
In this puzzle, we show how to sort a dictionary not after the keys but after the values. Recap, a dictionary stores (key, value) pairs. In our example, the keys are strings with the names of five different foods such as ‘Eggs’. The dictionary maps each food name to a numerical value that describes the amount of healthy Omega 3 fats per 100g.
How to sort the foods (keys) in the dictionary with respect to how much Omega 3 they contain (value)? To achieve this, we use Python’s built-in sorted function. Yet, calling sorted(omega3_table)
leads to a strange result. When applying the default sorted function to a dictionary, sorting is done with respect to the keys, not the values.
To fix this, we specify the key parameter of the sorted function. The key parameter expects a function that assigns a value to each element in the sequence. This value is then used to sort the sequence. In our example, we use the dictionary value of the respective key. We assign the value omega3_table[x]
to each sequence element x.
Python by default sorts in an ascending order. Hence, the last element of the sorted sequence (with maximal Omega 3) is the food 'Flaxseeds'
. Takeaway: eat one tablespoon of flaxseeds per day! They are among the healthiest foods on our planet.
👉 Recommended Article: Pimp Your Smoothie – Dr. Greger’s Daily Dozens
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.