Skip to content

Effortlessly Sort Python Dict by Value

[

Sorting a Python Dictionary: Values, Keys, and More

by Ian Currie

You’ve got a dictionary, but you’d like to sort the key-value pairs. Perhaps you’ve tried passing a dictionary to the sorted() function but haven’t gotten the results you expected. In this tutorial, you’ll learn how to sort dictionaries in Python.

Table of Contents

  • Rediscovering Dictionary Order in Python
  • Understanding What Sorting A Dictionary Really Means
  • Sorting Dictionaries in Python
    • Using the sorted() Function
    • Getting Keys, Values, or Both From a Dictionary
    • Understanding How Python Sorts Tuples
    • Using the key Parameter and Lambda Functions
    • Selecting a Nested Value With a Sort Key
    • Converting Back to a Dictionary
  • Considering Strategic and Performance Issues
    • Using Special Getter Functions to Increase Performance and Readability
    • Measuring Performance When Using itemgetter()
    • Judging Whether You Want to Use a Sorted Dictionary
    • Comparing the Performance of Different Data Structures
    • Comparing the Performance of Sorting
    • Comparing the Performance of Lookups
  • Conclusion

Rediscovering Dictionary Order in Python

Before Python 3.6, dictionaries were inherently unordered. However, starting from Python 3.6, dictionaries started to conserve insertion order, and from Python 3.7, the insertion order has been guaranteed. This means that you can now rely on the order of elements in a dictionary.

Understanding What Sorting A Dictionary Really Means

When sorting a dictionary, it’s important to understand that the concept of sorting a dictionary by itself doesn’t make sense because dictionaries are inherently unordered data structures. However, you can extract the items from a dictionary and sort those.

Sorting Dictionaries in Python

Using the sorted() Function

To sort a dictionary, you can use the sorted() function and pass in the dictionary’s items as the argument. The sorted() function will return a new list containing the sorted key-value pairs.

my_dict = {"banana": 3, "apple": 2, "orange": 1}
sorted_dict = sorted(my_dict.items())
print(sorted_dict)

Output:

[('apple', 2), ('banana', 3), ('orange', 1)]

Getting Keys, Values, or Both From a Dictionary

If you only want to sort the keys or values of a dictionary, you can use the sorted() function with the key parameter.

To sort by keys:

my_dict = {"banana": 3, "apple": 2, "orange": 1}
sorted_keys = sorted(my_dict, key=lambda x: x)
print(sorted_keys)

Output:

['apple', 'banana', 'orange']

To sort by values:

my_dict = {"banana": 3, "apple": 2, "orange": 1}
sorted_values = sorted(my_dict, key=lambda x: my_dict[x])
print(sorted_values)

Output:

['orange', 'apple', 'banana']

To sort by both keys and values:

my_dict = {"banana": 3, "apple": 2, "orange": 1}
sorted_items = sorted(my_dict.items(), key=lambda x: (x[0], x[1]))
print(sorted_items)

Output:

[('apple', 2), ('banana', 3), ('orange', 1)]

Understanding How Python Sorts Tuples

When sorting a dictionary by its items, Python uses the natural order of the underlying data types. For example, it will sort strings alphabetically and integers numerically.

Using the key Parameter and Lambda Functions

The key parameter of the sorted() function allows you to specify a custom sorting key. This is useful when you want to sort the items based on a specific attribute or nested value.

students = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 20},
{"name": "Charlie", "age": 30}
]
sorted_students = sorted(students, key=lambda x: x["age"])
print(sorted_students)

Output:

[{'name': 'Bob', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}]

Selecting a Nested Value With a Sort Key

If you have a dictionary with nested values and you want to sort the items based on a nested attribute, you can use a lambda function to select the nested value.

students = [
{"name": "Alice", "grades": {"math": 90, "english": 95}},
{"name": "Bob", "grades": {"math": 85, "english": 80}},
{"name": "Charlie", "grades": {"math": 95, "english": 90}}
]
sorted_students = sorted(students, key=lambda x: x["grades"]["math"])
print(sorted_students)

Output:

[{'name': 'Bob', 'grades': {'math': 85, 'english': 80}}, {'name': 'Alice', 'grades': {'math': 90, 'english': 95}}, {'name': 'Charlie', 'grades': {'math': 95, 'english': 90}}]

Converting Back to a Dictionary

After sorting a dictionary, you might want to convert it back to a dictionary. You can do this by using a dictionary comprehension or the dict() constructor.

Using a dictionary comprehension:

my_dict = {"banana": 3, "apple": 2, "orange": 1}
sorted_dict = {k: v for k, v in sorted(my_dict.items())}
print(sorted_dict)

Output:

{'apple': 2, 'banana': 3, 'orange': 1}

Using the dict() constructor:

my_dict = {"banana": 3, "apple": 2, "orange": 1}
sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict)

Output:

{'apple': 2, 'banana': 3, 'orange': 1}

Considering Strategic and Performance Issues

When sorting dictionaries, there are some strategic and performance considerations to keep in mind.

Using Special Getter Functions to Increase Performance and Readability

If you’re sorting a large dictionary multiple times, you can use special getter functions like itemgetter() to improve performance and readability.

from operator import itemgetter
my_dict = {"banana": 3, "apple": 2, "orange": 1}
getter = itemgetter(0)
sorted_dict = sorted(my_dict.items(), key=getter)
print(sorted_dict)

Output:

[('apple', 2), ('banana', 3), ('orange', 1)]

Measuring Performance When Using itemgetter()

You can measure the performance of sorting a dictionary using itemgetter() by using the timeit module.

import timeit
from operator import itemgetter
my_dict = {"banana": 3, "apple": 2, "orange": 1}
getter = itemgetter(0)
def sort_dict():
return sorted(my_dict.items(), key=getter)
execution_time = timeit.timeit(sort_dict, number=100000)
print(f"Execution time: {execution_time} seconds")

Output:

Execution time: 0.072073475 seconds

Judging Whether You Want to Use a Sorted Dictionary

While sorting dictionaries can be useful in some cases, it’s important to consider whether it’s the best option for your specific needs. Sorting a dictionary can take up extra memory and may not be necessary if you only need to access the key-value pairs in insertion order.

Comparing the Performance of Different Data Structures

If you’re working with large datasets and need to sort key-value data, you can also consider using alternative data structures like lists or pandas DataFrames. It’s worth comparing the performance of different data structures to find the most efficient solution for your problem.

Comparing the Performance of Sorting

In addition to comparing different data structures, you can also compare the performance of different sorting methods. This can help you determine the most efficient way to sort your key-value data.

Comparing the Performance of Lookups

When working with sorted dictionaries, it’s important to consider the performance of lookups. While sorting can be efficient, it may impact the performance of accessing specific key-value pairs.

Conclusion

Sorting dictionaries in Python can be done using the sorted() function and specifying a sort key. It’s important to understand that dictionaries are inherently unordered, but you can extract the items and sort them based on specific criteria. By considering strategic and performance issues, you can determine whether using a sorted dictionary is the best option for your particular use case.