In this tutorial, you will learn how to sort a Python dictionary by key or value.
When working with dictionaries in Python, you may need to sort their contents by key or value. Python dictionaries are key-value mappings, so create a new dictionary with the keys or values sorted as needed.
This tutorial begins by reviewing the basics of Python dictionaries. Next, you’ll learn how to create a new dictionary that sorts the content by key or value as needed.

The basics of Python dictionaries, revisited

What is a Python dictionary?
Dictionaries are Python’s built-in data structures. Store items as key-value pairs . You can use keys to search for corresponding values. Keys uniquely identify values, so keys should not be repeated.
py_dict = {"Python":"cool!","Learn":True}
py_dict["Python"]
# Output: cool!
py_dict["Learn"]
# Output: TrueFunctionally, dictionaries are similar to hash maps. Therefore, it does not necessarily have to be an ordered data structure. If you know the key, you can access the contents of the dictionary in any order.
Ordering items in a dictionary
In previous versions of Python, you had to use an OrderedDict to preserve key order. However, starting with Python 3.7, you can now access the items in the same order that you added them to the dictionary.
Now that you have learned the basics of Python dictionaries, let’s learn how to create a sorted copy of a dictionary.
⚙️Note : The code in this tutorial requires Python 3.7 or later to work as expected. You can download the latest version of Python or run the examples in the online Python editor.

How to sort a Python dictionary by key
Take a look at the image below of the cafe’s dessert menu. There are two columns corresponding to the menu items and their respective prices.
We can represent this in the form of a Python dictionary by collecting the name of the item as the key and its price as the value.
Let’s create a dictionary desserts as shown below.
desserts = {
"Ice cream":10,
"Brownies":12,
"Cheesecake":3,
"Swiss roll":5,
"Cookies":4,
"Cup cake":2
} Next, let’s create a dictionary sorted_desserts that sorts the desserts alphabetically. In the original desserts dictionary, the name of the dessert is key. Therefore, to create a new dictionary, these keys must be sorted alphabetically.
How to access keys in a Python dictionary
To do this, first get the keys of the dictionary and sort them alphabetically.
In Python, you can use the built-in dictionary method
.keys()to get a list of all the keys in a dictionary.
Let’s call .keys() method on the dessert dictionary to get the keys as shown below.
keys = desserts.keys()
print(keys)
#Output
['Ice cream', 'Brownies', 'Cheesecake', 'Swiss roll', 'Cookies',
'Cup cake']Calling Python’s built-in
sorted()function with a list as an argument returns a new sorted list.
Next, let’s call the sorted() function specifying keys of the list as an argument and store the sorted list in the variable sorted_keys .
sorted_keys = sorted(keys)
print(sorted_keys)
# Output
['Brownies', 'Cheesecake', 'Cookies', 'Cup cake', 'Ice cream', 'Swiss roll'] Now that the keys are sorted alphabetically, we can search desserts dictionary for the values corresponding to the keys in sorted_keys , as shown below.
sorted_desserts = {}
for key in sorted_keys:
sorted_desserts[key] = desserts[key]
print(sorted_desserts)
# Output
{'Brownies': 12, 'Cheesecake': 3, 'Cookies': 4, 'Cup cake': 2,
'Ice cream': 10, 'Swiss roll': 5}Let’s extend the code block above.
- Initialize
sorted_dessertsto be an empty Python dictionary. - Loop through the key list
sorted_keys. - For each key in
sorted_keys, find the corresponding value in thedessertsdictionary and add an entry tosorted_desserts.
Using a for loop like this is considered redundant. Python has a more concise alternative using dictionary comprehensions.
Understanding dictionaries in Python
Python supports the use of dictionary comprehensions as well as list comprehensions. Dictionary comprehensions allow you to create new Python dictionaries with just one line of code.
▶️ Here are some common constructs for using dictionary comprehensions in Python:
# 1. when you have both keys and values in two lists: list1, list2
new_dict = {key:value for key,value in zip(list1,list2)}
# 2. when you have the keys, and can look up the values
new_dict = {key:value for key in <iterable>} Let’s create sorted_desserts dictionary using the second construct new_dict = {key:value for key in <iterable>} in the cell above.
In this example:
- iterable : list
sorted_keys - Keys accessed by looping through key :sorted_keys
- value : Find the value corresponding to the key from the desserts dictionary,
desserts[key]
Putting these together, we get the following formula for dictionary understanding.
sorted_desserts = {key:desserts[key] for key in sorted_keys}
print(sorted_desserts)
{'Brownies': 12, 'Cheesecake': 3, 'Cookies': 4, 'Cup cake': 2,
'Ice cream': 10, 'Swiss roll': 5} From the above output, the desserts are ordered alphabetically within the sorted_desserts dictionary.

How to sort a Python dictionary by value
Next, learn how to sort a Python dictionary by value.
In the desserts dictionary, the value corresponds to the price of the dessert. You can sort the dictionary in ascending or descending order by price.
▶️ You can use the built-in dictionary method .items() to get all key-value pairs. Each tuple is a key-value pair.
desserts.items()
dict_items([('Ice cream', 10), ('Brownies', 12), ('Cheesecake', 3),
('Swiss roll', 5), ('Cookies', 4), ('Cup cake', 2)])Each item is itself a tuple. Therefore, you can also access each key and value individually by indexing each key-value pair.
dict_items = desserts.items()
for item in dict_items:
print(f"key:{item[0]},value:{item[1]}")
# Output
key:Ice cream,value:10
key:Brownies,value:12
key:Cheesecake,value:3
key:Swiss roll,value:5
key:Cookies,value:4
key:Cup cake,value:2Since we want to sort by value, we use the above method to get the value at index 1 of the key-value pair.
How to sort values in a Python dictionary in ascending order
This time we will use sorted() function and the optional key parameter. key can be any Python function, built-in function, user-defined function, or lambda function .
Note :
lambda args: expressionis the syntax for defining lambda functions in Python.
In this example of sorting desserts by price, you can access dictionary items (key-value pairs). Since we want to sort by value (price), set key = lambda item:item[1] .
The sorted() function returns a list by default, so you need to explicitly cast the list to dict , as shown below.
sorted_desserts = dict(sorted(desserts.items(), key=lambda item:item[1]))
print(sorted_desserts)
{'Cup cake': 2, 'Cheesecake': 3, 'Cookies': 4, 'Swiss roll': 5,
'Ice cream': 10, 'Brownies': 12}As explained earlier, it can also be rewritten using dictionary comprehension .
sorted_desserts = {key:value for key, value in sorted(desserts.items(),
key=lambda item:item[1])}
print(sorted_desserts)
# Output
{'Cup cake': 2, 'Cheesecake': 3, 'Cookies': 4, 'Swiss roll': 5,
'Ice cream': 10, 'Brownies': 12} In sorted_desserts , $2 Cup Cake is the first item and $12 Brownies is the last item.
How to sort values in a Python dictionary in descending order
If you want to sort prices in descending order, you can set the optional reverse parameter to True , as described below.
sorted_desserts = dict(sorted(desserts.items(), key=lambda item:item[1],
reverse=True))
print(sorted_desserts)
# Output
{'Brownies': 12, 'Ice cream': 10, 'Swiss roll': 5, 'Cookies': 4,
'Cheesecake': 3, 'Cup cake': 2}
Here, sorted_desserts is sorted in descending order of price, starting with the most expensive desserts, Brownies , at $12.
Summary 👩🏽💻
Let’s quickly summarize everything we learned in this tutorial.
- Python dictionaries store data in key-value pairs. All keys must be unique.
- The process of sorting a dictionary by key or value creates a new dictionary that can be sorted as needed.
- You can use the built-in dictionary methods .keys() and .items() to retrieve all keys and key-value pairs, respectively.
- To do the sorting you want, you can use the sorted() function with the optional parameters key and reverse .
Now that you’ve learned how to sort a Python dictionary, it’s time to learn how to sort a Python list. Have fun coding!🎉




![How to set up a Raspberry Pi web server in 2021 [Guide]](https://i0.wp.com/pcmanabu.com/wp-content/uploads/2019/10/web-server-02-309x198.png?w=1200&resize=1200,0&ssl=1)











































