When you’re working with a dictionary in Python, there are times when you’ll need to sort its contents—by key or by value. As a Python dictionary is a key-value mapping, you’ll create a new dictionary that has the keys or values sorted as needed. In this tutorial, we’ll start by reviewing the basics of Python dictionary. We’ll then learn to create a new dictionary in which the contents are sorted by key or by value, as needed.
Python Dictionary Basics, Revisited
What is a Python Dictionary?
Dictionary is a built-in data structure in Python. It stores items as key-value pairs. You can use the keys to look up the corresponding values. As the keys uniquely identify the values, there should be no repetition of keys. Functionally, a dictionary is similar to a hash map. Therefore, it is not necessarily an ordered data structure. You can access the contents of a dictionary in any arbitrary order, so long as you know the keys.
Ordering of Items in a Dictionary
In earlier versions of Python, you had to use an OrderedDict to preserve the order of the keys. However, from Python 3.7, you can access the items in the same order in which you add them to the dictionary. Now that you’ve learned the basics of Python dictionaries, let’s learn how to create sorted copies of the dictionary.
How to Sort a Python Dictionary by Key
Look at the following image of the dessert menu at a café. There are two columns corresponding to the items on the menu and their respective prices. You can represent this in the form of a Python dictionary by collecting the names of items as keys and their prices as values. Let’s go ahead and create the dictionary desserts, as shown below. Next, let’s create a dictionary sorted_desserts, where the desserts are arranged in alphabetical order. In the original desserts dictionary, the names of the desserts are the keys. So you should sort these keys in alphabetical order to create a new dictionary.
How to Access the Keys of a Python Dictionary
To do this, we’ll first get the keys of the dictionary and then sort them in alphabetical order. Let’s call the .keys() method on the dessert dictionary to retrieve the keys, as shown below. Next, let’s call the sorted() function with the list keys as the argument and store the sorted list in the variable sorted_keys. Now that we have the keys sorted in alphabetical order, we can look up the values corresponding to the keys in sorted_keys from the desserts dictionary, as shown below. Let’s expand on the above block of code:
Initialize sorted_desserts to be an empty Python dictionary.Loop through the keys list sorted_keys.For each key in sorted_keys, add an entry to sorted_desserts by looking up the corresponding value in the desserts dictionary.
Using the for loop like this is considered verbose. In Python, there’s a more concise alternative using dictionary comprehension.
Dictionary Comprehension in Python
Python supports the use of dictionary comprehension, similar to list comprehension. Dictionary comprehension lets you create a new Python dictionary with just one line of code.
▶️ Here’s the general construct to use dictionary comprehension in Python.
Let’s use the second construct in the above cell: new_dict = {key:value for key in
iterable: the list sorted_keyskey: the key that we access by looping through sorted_keysvalue: look up the value corresponding to the key from the desserts dictionary, desserts[key]
Putting it all together, we have the expression for dictionary comprehension, as shown below. From the above output, the desserts are arranged in alphabetical order in the sorted_desserts dictionary.
How to Sort a Python Dictionary by Value
Next, we’ll learn how to sort a Python dictionary by its values. In the desserts dictionary, the values correspond to the prices of the desserts. You may want to sort the dictionary by prices, either in increasing or decreasing order. ▶️ You can use the built-in dictionary method .items() to get all the key-value pairs. Each tuple is a key-value pair. Each of the items is a tuple in itself. So you can also index into each key-value pair to access the keys and values individually. As we would like to sort by values, we’ll use the above method to get the value at index 1 in the key-value pair.
How to Sort the Values of a Python Dictionary in Increasing Order
This time, we’ll use the sorted() function along with the optional key parameter. key can be any Python function, a built-in function, a user-defined function, or even a lambda function. In this example of sorting desserts by price, we have access to dictionary items (key-value pairs). We’ll set key = lambda item:item[1] as we’d like to sort by the value (price). As sorted() function returns a list by default, you should explicitly cast it into a dict, as shown below. You can also rewrite using dictionary comprehension, as discussed earlier. In sorted_desserts, Cup Cake priced at $2 is the first item and Brownies priced at $12 is the last item.
How to Sort the Values of a Python Dictionary in Decreasing Order
If you’d like to sort the prices in decreasing order, you can set the optional reverse parameter to True, as explained below. Now, sorted_desserts has been sorted in the decreasing order of prices, starting with the most expensive dessert Brownies costing $12.
Wrapping Up 👩🏽💻
Let’s quickly summarize all that we’ve learned in this tutorial.
A Python dictionary stores data in key-value pairs; the keys should all be unique.In the process of sorting a dictionary by key or value, we create a new dictionary that is sorted as needed.You can use the built-in dictionary methods, .keys() and .items() to retrieve all the keys and key-value pairs, respectively.You can use the sorted() function along with the optional parameters key and reverse to achieve the desired sorting.
Now that you’ve learned how to sort a Python dictionary, learn to sort Python lists. Happy coding!🎉