Tutorial

3 ways to sort dictionary by value in Python

4 min read

This article will walk you through several ways to sort dictionary by value in Python, explaining how each approach works and when to use it.

Sorting a dictionary by value can simplify your data manipulation tasks, allowing you to access the most relevant information quickly.

However, it’s important to note that dictionaries cannot be sorted in place—you must create a new, sorted dictionary.

Introduction

Python dictionaries are data structures used to store key-value pairs. However, unlike lists or tuples, dictionaries are unordered. The sequence in which we define the keys and values does not impact the dictionary itself.

Starting from Python 3.7, dictionaries preserve the insertion order, but this does not mean they are sorted by their keys or values.

Sometimes, you may want to sort a dictionary by its values, for example, when you need to rank items by their occurrence or filter the most important data points.

What does it mean to sort a dictionary?

We need to first break down the concept of sorting in Python.

A dictionary is a collection of key-value pairs, where each key is associated with a value.

When we say we want to “sort a dictionary by value,” we are essentially rearranging the key-value pairs based on the value in ascending or descending order.

Since Python dictionaries maintain insertion order starting from version 3.7, sorting them by value allows you to recreate the dictionary with the key-value pairs ordered accordingly.

Unlike lists or arrays, dictionaries cannot be sorted directly.

The sorting process generates a new dictionary where the items are rearranged based on the sorting criteria you define, such as sorting by the numerical or alphabetical value associated with each key.

Sort dictionary by value in Python using sorted() Function

One of the most straightforward ways to sort a dictionary by value in Python is by using built-in sorted() function.

This function allows you to pass an iterable (such as the dictionary’s items) and specify a sorting criterion using the key argument. For dictionaries, this means sorting the items based on their values.

The sorted() function generates a list of tuples containing key-value pairs, which can be used to construct a new dictionary.

For example:

d = {'apple': 500, 'banana': 1500, 'orange': 1, 'pineapple': 789} 
sorted_dict = {k: v for k, v in sorted(d.items(), key=lambda item: item[1])} 
print(sorted_dict)

Output:

Sort dictionary by value in Python using sorted() function and lambda

The dictionary is sorted in ascending order by value.

The sorted() function takes each key-value pair, applies the lambda function (lambda item: item[1]) to extract the value, and arrange the dictionary accordingly.

The result is a new dictionary where the fruits are listed by increasing price.

Sort dictionary by value in Python using operator.itemgetter

For larger dictionaries where performance is important, using operator.itemgetter(1) can be more efficient than using a lambda function.

The itemgetter function is optimized to directly access the values of a dictionary, avoiding the overhead that comes with defining a lambda function.

from operator import itemgetter 

grades = {'John': 85, 'Alice': 92, 'Bob': 70, 'Diana': 88} 
sorted_grades = dict(sorted(grades.items(), key=itemgetter(1))) 
print(sorted_grades)

Output:

Output of sorted dictionary by value in Python using operator.itemgetter

In this example, the dictionary is sorted by student grades in ascending order.

While this approach achieves the same goal as using a lambda function, itemgetter tends to be more performant when handling larger datasets due to its optimized internal operations.

Keep in mind, though, that the output will vary depending on the values in the dictionary.

Sort a Numeric values dictionary using  Counter

When working with Python dictionaries that represent counts or frequencies, the Counter class from the collections module is a powerful tool.

One of its key features is the most_common() method, which sorts the dictionary by value in descending order.

This is especially useful for tasks like ranking or determining the most frequent occurrences.

from collections import Counter

city_population = {'New York': 8500000, 'Los Angeles': 4000000, 'Chicago': 2700000, 'Houston': 2300000}
counter = Counter(city_population)
sorted_population = dict(counter.most_common())
print(sorted_population)

Output:

output of sorted dictionary using counter and most_common function

In this example, the cities are sorted by their population, with the largest populations appearing first.

The most_common() method is particularly effective in scenarios where you need to quickly rank items by size or frequency, making it ideal for datasets involving counts or numeric values.

Sorting a dictionary by value in Python provides a powerful way to organize and access important data more efficiently.

Whether you’re working with small datasets or large collections, choosing the right method, such as sorted(), itemgetter(), or Counter(), allows for clear and structured data manipulation.