How to sort a Python dictionary by its values?

PythonPythonBeginner
Practice Now

Introduction

Python dictionaries are versatile data structures that allow you to store and retrieve key-value pairs. In this tutorial, we will explore how to sort a Python dictionary by its values, empowering you to organize and analyze your data more effectively. By the end of this guide, you will have a solid understanding of various sorting techniques and be able to apply them to your Python projects.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") subgraph Lab Skills python/dictionaries -.-> lab-398247{{"`How to sort a Python dictionary by its values?`"}} python/data_collections -.-> lab-398247{{"`How to sort a Python dictionary by its values?`"}} end

Understanding Python Dictionaries

Python dictionaries are powerful data structures that allow you to store and manipulate key-value pairs. They are widely used in various programming tasks, from data processing to building complex applications.

What is a Python Dictionary?

A Python dictionary is an unordered collection of key-value pairs. Each key in a dictionary must be unique, and it is used to access the corresponding value. Dictionaries are denoted by curly braces {}, and the key-value pairs are separated by colons :.

Here's an example of a simple dictionary:

person = {
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

In this example, the keys are "name", "age", and "city", and the corresponding values are "John Doe", 30, and "New York".

Accessing and Modifying Dictionary Elements

You can access the values in a dictionary using their corresponding keys. For example:

print(person["name"])  ## Output: "John Doe"
print(person["age"])   ## Output: 30

You can also add, modify, or remove key-value pairs in a dictionary:

person["email"] = "john.doe@example.com"  ## Adding a new key-value pair
person["age"] = 31                       ## Modifying an existing value
del person["city"]                       ## Removing a key-value pair

Common Dictionary Operations

Python dictionaries provide a wide range of built-in methods and operations, such as:

  • len(person): Returns the number of key-value pairs in the dictionary.
  • person.keys(): Returns a view object containing all the keys in the dictionary.
  • person.values(): Returns a view object containing all the values in the dictionary.
  • person.items(): Returns a view object containing all the key-value pairs in the dictionary.
  • "name" in person: Checks if a key exists in the dictionary.

Understanding the basics of Python dictionaries is crucial before diving into sorting them by their values, which will be covered in the next section.

Sorting Dictionaries by Values

Sorting a dictionary by its values is a common task in Python programming. While dictionaries are inherently unordered, you can use various techniques to sort them based on their values.

Using the sorted() Function

The built-in sorted() function in Python can be used to sort a dictionary by its values. The sorted() function returns a new list of tuples, where each tuple contains a key-value pair from the original dictionary.

Here's an example:

person = {
    "Alice": 25,
    "Bob": 32,
    "Charlie": 19,
    "David": 28
}

sorted_person = sorted(person.items(), key=lambda x: x[1])
print(sorted_person)

Output:

[('Charlie', 19), ('Alice', 25), ('David', 28), ('Bob', 32)]

In this example, the sorted() function takes the items() method of the person dictionary as input, and the key parameter is used to specify the sorting criteria. In this case, the key function lambda x: x[1] sorts the dictionary based on the values (the second element of each tuple).

Using the dict() Function

You can also convert the sorted list of tuples back into a dictionary using the dict() function:

sorted_person_dict = dict(sorted(person.items(), key=lambda x: x[1]))
print(sorted_person_dict)

Output:

{'Charlie': 19, 'Alice': 25, 'David': 28, 'Bob': 32}

This approach preserves the original key-value associations while sorting the dictionary by its values.

Sorting in Reverse Order

To sort the dictionary in reverse order (from highest to lowest value), you can use the reverse=True parameter in the sorted() function:

sorted_person = sorted(person.items(), key=lambda x: x[1], reverse=True)
print(sorted_person)

Output:

[('Bob', 32), ('David', 28), ('Alice', 25), ('Charlie', 19)]

By understanding these techniques, you can effectively sort Python dictionaries by their values to meet your specific needs.

Advanced Sorting Techniques

While the previous methods provide a straightforward way to sort dictionaries by their values, Python also offers more advanced techniques that can be useful in certain scenarios.

Using the itemgetter Function

The operator module in Python provides the itemgetter function, which can be used as an alternative to the lambda function in the sorted() call. This can make the code more readable, especially when sorting by multiple keys.

from operator import itemgetter

person = {
    "Alice": 25,
    "Bob": 32,
    "Charlie": 19,
    "David": 28
}

sorted_person = sorted(person.items(), key=itemgetter(1))
print(sorted_person)

Output:

[('Charlie', 19), ('Alice', 25), ('David', 28), ('Bob', 32)]

In this example, itemgetter(1) is used to specify that the sorting should be based on the second element (the value) of each key-value pair.

Sorting by Multiple Keys

Sometimes, you may need to sort a dictionary by multiple keys. You can achieve this by using a tuple as the key function in the sorted() call.

person = {
    "Alice": (25, "New York"),
    "Bob": (32, "London"),
    "Charlie": (19, "Paris"),
    "David": (28, "Tokyo")
}

sorted_person = sorted(person.items(), key=lambda x: (x[1][1], x[1][0]))
print(sorted_person)

Output:

[('Charlie', (19, 'Paris')), ('David', (28, 'Tokyo')), ('Alice', (25, 'New York')), ('Bob', (32, 'London'))]

In this example, the sorting is first based on the second element of the value tuple (the city), and then on the first element (the age).

By exploring these advanced sorting techniques, you can handle more complex sorting requirements for your Python dictionaries.

Summary

Sorting a Python dictionary by its values is a fundamental skill that can greatly enhance your data management and analysis capabilities. In this tutorial, you have learned how to leverage built-in functions and custom sorting methods to sort dictionaries, unlocking new possibilities for data manipulation and organization within your Python programs. With these techniques, you can optimize your workflows, gain deeper insights, and create more efficient and effective Python applications.

Other Python Tutorials you may like