Python: Sort a Dictionary by Values

Python Sort Dictionary by Its Values Cover Image

In this tutorial, you’ll learn how to use Python to sort a dictionary by their values. Beginning in Python 3.7, dictionaries became ordered.

Sorting a dictionary can have tremendous benefits. Say you’re storing your clients’ information by name. Sorting the data reduces its complexity tremendously, making the data easier to work with.

The Quick Answer: Use dict.items() and sorted()

Quick Answer - Python Sort Dictionary by Values

Why Sort a Python Dictionary

Python dictionaries are incredibly useful data structures. They stored data in key:value pairs, allowing us to retrieve data very easily. Beginning in Python 3.7, Python dictionaries become ordered, meaning that their order can be changed to improve efficiency.

Sorting a dictionary by the key’s values can help in efficiency if you’re frequently identifying keys with either maximum or minimum values. Say you’re keeping track of players’ scores and need to access the players with the highest and lowest scores more frequently. Sorting your dictionary, then, becomes a tool that allows you to optimize retrieval.

Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.

Sort a Python Dictionary by Values Using dict.items and Sorted

The Python sorted() function allows us to, well, sort an item. The sorted() function accepts three parameters:

  1. iterable: An item to sort
  2. key: The key to sort by
  3. reverse: Whether to sort in reverse order or not

The key is the method by which to sort data. In essence, it’s a function that’s evaluated in order to compare against how to sort.

Because we want to compare against the items’ values, we will use key=item.get, which returns a key’s value.

Let’s see what this looks like in practice:

# Sorting a Dictionary by its values using sorted()

sales = {
    'apples': 12,
    'bananas': 32,
    'oranges': 24,
    'grapes': 43,
    'tangerines': 55
}

sorted = sorted(sales, key=sales.get)
sorted_dict = {}
for key in sorted:
    sorted_dict[key] = sales[key]

print(sorted_dict)

# Returns: {'apples': 12, 'oranges': 24, 'bananas': 32, 'grapes': 43, 'tangerines': 55}

Let’s take a look at what we’ve done here. We generated a list, using the sorted() function that returns the values in ascending order. We then looped over the generated new key:pair values in our new dictionary sorted_dict.

We can also skip the step of first creating the list and then looping over it by using a slightly tweaked reverse() function. Let’s see how we can trim this down:

# Sorting a Dictionary by its values using sorted()

sales = {
    'apples': 12,
    'bananas': 32,
    'oranges': 24,
    'grapes': 43,
    'tangerines': 55
}

sorted = dict(sorted(sales.items(), key=lambda x: x[1]))

print(sorted)

# Returns: {'apples': 12, 'oranges': 24, 'bananas': 32, 'grapes': 43, 'tangerines': 55}

In this example, we’ve cut out a decent amount of code. Let’s break this down a bit:

  1. We pass in the sales.items(), which returns tuples of key:value pairs
  2. We then use the lambda function that grabs the second item in the pair (the value)
  3. We finally turn this back into a dictionary using the dict() function

If we wanted to sort the values in descending order, you could also pass in the reverse=True argument.

In the next section, you’ll learn how to use a Python for loop to sort a dictionary by its values.

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

Sort a Python Dictionary by Values Using a For Loop

In this section, you’ll learn how to use a Python for loop to sort a dictionary by its values.

We’ll use the Python reverse() function again and loop over the resulting list of tuples. We’ll then assign new key:pair values to a dictionary that will store our sorted dictionary.

Let’s see how we can do this in Python:

# Sorting a Dictionary by its values using sorted() and a for loop

sales = {
    'apples': 12,
    'bananas': 32,
    'oranges': 24,
    'grapes': 43,
    'tangerines': 55
}

sorted_dict = {}
for key, value in sorted(sales.items(), key=lambda x: x[1]):
    sorted_dict[key] = value
print(sorted_dict)

# Returns: {'apples': 12, 'oranges': 24, 'bananas': 32, 'grapes': 43, 'tangerines': 55}

Here, we loop over the generated list of tuples, including both its keys and values. We then assign the key and value pair to the new dictionary.

In the next section, you’ll learn how to sort a dictionary by its values using a Python list comprehension.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Sort a Python Dictionary by Values Using a Dictionary Comprehension

We can turn the above for loop into a dictionary comprehension, which cuts down the amount of code we need to write. In fact, turning this into a dictionary comprehension makes the entire code more readable.

New to dictionary comprehensions? Check out my in-depth tutorial on them here, which covers off everything you need to know.

The image below provides an easy-to-read overview of Python dictionary comprehensions:

Python Dictionary Comprehension overview

Let’s see how we can use a Python dictionary comprehension to sort a dictionary by its values:

# Sorting a Dictionary by its values using sorted() and a dictionary comprehension

sales = {
    'apples': 12,
    'bananas': 32,
    'oranges': 24,
    'grapes': 43,
    'tangerines': 55
}

sorted_dict = {key:value for key, value in sorted(sales.items(), key=lambda x: x[1])}
print(sorted_dict)

# Returns: {'apples': 12, 'oranges': 24, 'bananas': 32, 'grapes': 43, 'tangerines': 55}

In the next section, you’ll learn how to use a lambda function to sort a dictionary by its values.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

Conclusion

In this tutorial, you learned how to sort a Python dictionary by its values. You learned how to do this using the dict.items() method, a Python for loop, a list comprehension, and a lambda function.

To learn more about Python dictionaries, check out the official documentation here.