Sentry Answers>Python>

Sort a dictionary by value in Python

Sort a dictionary by value in Python

David Y.

The ProblemJump To Solution

How can I sort a dictionary by value in Python?

The Solution

Python dictionaries were originally intended to be used for data that does not have a meaningful order. In older versions of Python, no order is guaranteed. However, as of Python 3.7, key-value pairs in Python dictionaries are ordered according to when they were inserted. This means that we can sort a dictionary by sorting its key-value pairs and creating a new dictionary from them. The code below shows how to do this:

Click to Copy
prices = {"Orange": 3, "Avocado": 5, "Apple": 1, "Pear": 2, "Grapefruit": 4} prices_sorted = dict(sorted(prices.items(), key=lambda item: item[1])) print(prices_sorted) # will output {"Apple": 1, "Pear": 2, "Orange": 3, "Grapefruit": 4, "Avocado": 5}

Here we use Python’s built-in sorted() function to sort our dictionary’s items (i.e. its key-value pairs) by value, ascending. We then convert the output of sorted(), which will be a list of tuples, into a new dictionary. As items will be inserted into our new dictionary in order of their values, we now have a dictionary ordered by value.

In older versions of Python, we would need to use an OrderedDict from Python’s built-in collections module in place of an ordinary dictionary, as shown below:

Click to Copy
from collections import OrderedDict prices = {"Orange": 3, "Avocado": 5, "Apple": 1, "Pear": 2, "Grapefruit": 4} prices_sorted = OrderedDict(sorted(prices.items(), key=lambda item: item[1])) print(prices_sorted) # will output OrderedDict([("Apple", 1), ("Pear", 2), ("Orange", 3), ("Grapefruit", 4), ("Avocado", 5)])
  • Sentry BlogPython Performance Testing: A Comprehensive Guide
  • Sentry BlogLogging in Python: A Developer’s Guide
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty Treats for Web Developers brought to you by Sentry. Web development tips and tricks hosted by Wes Bos and Scott Tolinski

    Listen to Syntax

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.