In this tutorial, you will learn how to sort a Python dictionary by its key or value.

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.

py_dict = {"Python":"cool!","Learn":True}
py_dict["Python"]
# Output: cool!

py_dict["Learn"]
# Output: True

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.

⚙️ Note: You need to have Python 3.7 or later for the code in this tutorial to work as expected. You can download the latest version of Python, or run the examples in Geekflare Online Python Editor.

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.

<img alt="python-dictionary-from-data" data- data-src="https://kirelos.com/wp-content/uploads/2022/06/echo/Dessert-Time-1-1500×844.png" data- height="844" src="data:image/svg xml,” width=”1500″>

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.

desserts = {
    "Ice cream":10,
    "Brownies":12,
    "Cheesecake":3,
    "Swiss roll":5,
    "Cookies":4,
    "Cup cake":2
}

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.

In Python, you can use the built-in dictionary method .keys() to get a list of all the keys in the dictionary.

Let’s call the .keys() method on the dessert dictionary to retrieve 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 the argument returns a new sorted list.

Next, let’s call the sorted() function with the list keys as the 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 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.

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 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.

# 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 }

Let’s use the second construct in the above cell: new_dict = {key:value for key in } to create a sorted_desserts dictionary.

In this example:

  • iterable: the list sorted_keys
  • key: the key that we access by looping through sorted_keys
  • value: 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.

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 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.

desserts.items()

dict_items([('Ice cream', 10), ('Brownies', 12), ('Cheesecake', 3), 
('Swiss roll', 5), ('Cookies', 4), ('Cup cake', 2)])

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.

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:2

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.

Note: lambda args: expression is the syntax for defining lambda functions in Python.

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.

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}

You can also rewrite using dictionary comprehension, as discussed earlier.

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, 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.

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}

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!🎉