~ 3 min read

Sorting Python Dictionaries by Keys and Values

By: Adam Richardson
Share:

Sorting Python Dictionaries by Keys and Values

Introduction

As a Python developer, working with dictionaries is an essential skill. Dictionaries store data in key-value pairs, and sorting them can be useful for tasks like analyzing data or generating reports. This article addresses how to perform sorting in Python dictionaries, which can help create more efficient and cleaner code.

Properties and Parameters

A Python dictionary, also known as a “hash table” or “hash map,” is an unordered collection of key-value pairs, where each key must be unique. The primary types of sorting methods for dictionaries involve either the keys or the values. Dictionary sorting can be done using the following built-in Python functions:

  • sorted(): This function returns a sorted list of the specified iterable. It takes three optional parameters:

    • iterable: The sequence to sort, such as a list, tuple, or dictionary.
    • key: A custom function to customize the sorting; it takes one argument and returns one value to be compared.
    • reverse: Boolean, if set to True, then the iterable will be sorted in reverse order.
  • lambda: A small, anonymous function used to define and pass functions as parameters to other functions. It’s a useful tool in sorting dictionaries with the sorted() function.

Simplified Real-Life Example

Imagine you have a dictionary containing the names and ages of a group of people. You would like to sort the dictionary by their ages:

ages_dict = {'Emma': 25, 'Liam': 30, 'Olivia': 28, 'Noah': 22}

# Sort by age (values)
sorted_ages = {k: v for k, v in sorted(ages_dict.items(), key=lambda item: item[1])}

print(sorted_ages)

This code would output:

{'Noah': 22, 'Emma': 25, 'Olivia': 28, 'Liam': 30}

In this example, the sorted() function is used to sort the dictionary by its values (ages). The key parameter gets the value from each key-value pair using a lambda function, and the resultant list comprehension creates a new dictionary with the sorted data.

More Complex Real-Life Example

Let’s consider a more complex scenario. You have a dictionary containing the names of students and their respective grade point averages (GPAs). You want to rank and display the top three students:

gpa_dict = {
    'Alison': 3.7,
    'Benjamin': 3.9,
    'Carla': 3.3,
    'David': 3.5,
    'Ella': 3.85,
    'Frank': 3.7,
    'Grace': 3.5,
}

# Sort by GPA (values) in descending order and slice the top 3
sorted_gpas_desc = {k: v for k, v in sorted(gpa_dict.items(), key=lambda item: item[1], reverse=True)[:3]}

print("Top 3 students:")
for student, gpa in sorted_gpas_desc.items():
    print(f"{student}: {gpa}")

This code would output:

Top 3 students:
Benjamin: 3.9
Ella: 3.85
Alison: 3.7

In this case, we sorted the dictionary by its values (GPAs) in descending order by setting the reverse parameter to True in the sorted() function. Then, we used list slicing to get the top three students.

Personal Tips

  1. Dictionaries in Python 3.7 onwards maintain the order of insertion. Earlier versions do not guarantee this behavior.
  2. Although you can use the sorted() function with custom key and reverse parameters, you can also use custom sorting functions to gain more control over the sorting process.
  3. While working with larger datasets, consider using external libraries like Pandas or NumPy for better performance and convenience when sorting dictionaries.
  4. Always prefer readability and clarity in your code, especially since Python dictionaries can be handled in a variety of ways for the same operation. Choose the method that works best for your use case and is easy to understand for other developers.
Share:
Subscribe to our newsletter

Stay up to date with our latest content - No spam!

Related Posts