Sort a dictionary by value in Python

David Y.

The Problem

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:

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:

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)])

Get Started With Sentry

Get actionable, code-level insights to resolve Python performance bottlenecks and errors.

  1. Create a free Sentry account

  2. Create a Python project and note your DSN

  3. Grab the Sentry Python SDK

pip install --upgrade sentry-sdk
  1. Configure your DSN
import sentry_sdk sentry_sdk.init( "https://<key>@sentry.io/<project>", # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, )

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.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

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