Lightning bolt and Python code snippet with "PYTHON SORT DICTIONARY BY VALUE" in blocky caps

Sort Dictionary by Value Python Deep Dive!

In Python, dictionaries are widely used for storing key-value pairs, where each key maps to a specific value. While dictionaries maintain the insertion order of keys in Python 3.7 and later, you may often need to sort a dictionary by value to analyze or process data more effectively.

To sort dictionary by value Python provides a few different approaches, and by the end of this guide, you’ll have a deep understanding of how to do it apply them efficiently and when.

How Dictionaries Work in Python

A dictionary in Python is a collection of key-value pairs, where each key is unique and maps to a specific value. Unlike lists or tuples, dictionaries are unordered before Python 3.7. Starting from Python 3.7, dictionaries preserve the insertion order of keys, but they are still not inherently sorted by values.

Example of a Dictionary:

my_dict = {
    "apple": 3,
    "banana": 5,
    "orange": 2
}

In this dictionary, the keys are "apple", "banana", and "orange", while the corresponding values are 3, 5, and 2.

Sorting a Dictionary by Value in Python

To sort a dictionary by its values in Python, you need to convert the dictionary into a sortable format, such as a list of tuples or a sorted dictionary view. You can then use various functions like sorted() or itemgetter() to perform the sorting. Let’s explore different methods to achieve this.

1. Sorting a Dictionary by Value Using sorted() and lambda

The most common way to sort a dictionary by value is to use the sorted() function in combination with a lambda function to specify that sorting should be done based on the dictionary’s values.

Syntax:

sorted(dictionary.items(), key=lambda item: item[1])
  • dictionary.items(): Converts the dictionary into a list of key-value pairs (tuples).
  • key=lambda item: item[1]: Specifies that sorting should be done based on the value of each key-value pair (where item[1] is the value).

Example: Sorting in Ascending Order

my_dict = {
    "apple": 3,
    "banana": 5,
    "orange": 2
}

sorted_dict = sorted(my_dict.items(), key=lambda item: item[1])

print(sorted_dict)
Output:
[('orange', 2), ('apple', 3), ('banana', 5)]

In this example, the dictionary is sorted in ascending order by value, and the result is a list of tuples.

2. Sorting a Dictionary by Value in Descending Order

To sort the dictionary by value in descending order, you can pass the parameter reverse=True to the sorted() function.

Example: Sorting in Descending Order

my_dict = {
    "apple": 3,
    "banana": 5,
    "orange": 2
}

sorted_dict_desc = sorted(my_dict.items(), key=lambda item: item[1], reverse=True)

print(sorted_dict_desc)
Output:
[('banana', 5), ('apple', 3), ('orange', 2)]

Here, the dictionary is sorted in descending order based on the values.

Converting Sorted Data Back to a Dictionary

The sorted() function returns a list of tuples, but if you want the result to be a dictionary again, you can use dictionary comprehension or the dict() constructor to convert the sorted list back into a dictionary.

Example: Converting Sorted Tuples Back to a Dictionary

my_dict = {
    "apple": 3,
    "banana": 5,
    "orange": 2
}

# Sorting in ascending order and converting back to a dictionary
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))

print(sorted_dict)

Output:

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

Now, the dictionary is sorted by value and is presented in dictionary format.

Sorting a Dictionary by Value Using operator.itemgetter()

Another method to sort a dictionary by value is to use the operator.itemgetter() function from the operator module. This function allows you to specify which element of the tuple (key or value) you want to sort by, making it a more explicit alternative to lambda functions.

Example: Using itemgetter() to Sort by Value

import operator

my_dict = {
    "apple": 3,
    "banana": 5,
    "orange": 2
}

sorted_dict = sorted(my_dict.items(), key=operator.itemgetter(1))

print(sorted_dict)

Output:

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

This method is similar to using lambda but is often preferred for more complex sorting operations, as it can improve readability.

Sorting by Multiple Criteria

In some cases, you may want to sort by multiple criteria, such as sorting first by value and then by key to break ties. This can be done by combining sorting conditions in the key argument.

Example: Sorting by Value, then by Key

my_dict = {
    "apple": 3,
    "banana": 5,
    "orange": 2,
    "grape": 5
}

sorted_dict = sorted(my_dict.items(), key=lambda item: (item[1], item[0]))

print(sorted_dict)

Output:

[('orange', 2), ('apple', 3), ('banana', 5), ('grape', 5)]

Here, the dictionary is first sorted by value and then by key in alphabetical order for items with the same value.

Sorting a Nested Dictionary by Value

If you have a nested dictionary (a dictionary of dictionaries), you can sort it by accessing the values of the inner dictionaries.

Example: Sorting a Nested Dictionary by an Inner Value

nested_dict = {
    "item1": {"price": 100, "quantity": 20},
    "item2": {"price": 50, "quantity": 10},
    "item3": {"price": 150, "quantity": 5}
}

sorted_nested_dict = sorted(nested_dict.items(), key=lambda item: item[1]['price'])

print(sorted_nested_dict)

Output:

[('item2', {'price': 50, 'quantity': 10}), ('item1', {'price': 100, 'quantity': 20}), ('item3', {'price': 150, 'quantity': 5})]

In this example, the dictionary is sorted by the price value in the nested dictionaries.

Best Practices for Sorting a Dictionary by Value

1. Use sorted() for Readability and Simplicity

The sorted() function combined with lambda is the most common and straightforward way to sort a dictionary by value. It is easy to read, flexible, and works for most use cases.

Example:

sorted_dict = sorted(my_dict.items(), key=lambda item: item[1])

2. Use reverse=True for Descending Order

When you need to sort the dictionary in descending order, simply add the reverse=True argument to avoid having to manipulate the values manually.

Example:

sorted_dict_desc = sorted(my_dict.items(), key=lambda item: item[1], reverse=True)

3. Consider itemgetter() for Clarity in Complex Sorting

If you have more complex sorting requirements or need to sort by multiple fields, consider using operator.itemgetter() for better readability.

Example:

sorted_dict = sorted(my_dict.items(), key=operator.itemgetter(1))

Common Pitfalls to Avoid

1. Forgetting to Convert Back to a Dictionary

The sorted() function returns a list of tuples, not a dictionary. If you need the result to be in dictionary form, use dict() to convert it back.

Correct:

sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))

2. Sorting by Keys Instead of Values

Ensure that the key argument in the sorted() function refers to the value part of the tuple (item[1]). Sorting by item[0] will sort by the key instead of the value.

Correct:

sorted_dict = sorted(my_dict.items(), key=lambda item: item[1])

Summary of Key Concepts

  • Sorting a dictionary by value in Python can be done using the sorted() function combined with a lambda function or operator.itemgetter().
  • Use reverse=True to sort in descending order and dict() to convert the sorted list back into a dictionary.
  • Sorting by multiple criteria is possible by specifying a tuple in the key argument.
  • For nested dictionaries, you can sort by accessing the inner dictionary values.

Exercises

  1. Basic Sorting: Write a Python function that takes a dictionary as input and returns the dictionary sorted by values in ascending order.
  2. Sort by Value and Key: Modify the above function to first sort by value and then by key in case of ties.
  3. Nested Dictionary Sorting: Write a Python program that sorts a nested dictionary by one of the inner dictionary values, such as “price” or “quantity.”
Lightning bolt and Python code snippet with "LEARN PYTHON PROGRAMMING MASTERCLASS" in blocky caps

Check out our FREE Learn Python Programming Masterclass to hone your skills or learn from scratch.

The course covers everything from first principles to Graphical User Interfaces and Machine Learning

You can check out the official Python documentation on dictionaries here.

FAQ

Q1: Can I sort a dictionary by value without converting it to a list first?

A1: No, dictionaries in Python are inherently unordered collections of key-value pairs. To sort by value, you must convert the dictionary into an iterable format, like a list of tuples, which can be sorted. The most common approach is using dictionary.items() to convert the dictionary into a list of key-value pairs, which can then be sorted.

Q2: Can I keep the sorted dictionary as a dictionary, not a list of tuples?

A2: Yes, you can convert the sorted list of tuples back into a dictionary using the dict() function. However, remember that once you convert it back into a dictionary, the sorting order will be preserved only if you’re using Python 3.7 or later, where dictionaries maintain insertion order.

Example:

sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))

Q3: Can I sort a dictionary by both key and value at the same time?

A3: Yes, you can sort by both key and value by specifying multiple criteria in the key argument of the sorted() function. For example, you can first sort by value, and then by key in the case of ties.

Example:

sorted_dict = sorted(my_dict.items(), key=lambda item: (item[1], item[0]))

This will sort by value first, and if two values are the same, it will sort those items by key.

Q4: How do I sort a dictionary by value if the values are not numbers (e.g., strings)?

A4: You can still sort a dictionary by value even if the values are strings. Python’s sorted() function can sort any iterable, including strings, based on lexicographic order (alphabetical order for strings).

Example:

my_dict = {"apple": "orange", "banana": "apple", "orange": "banana"}
sorted_dict = sorted(my_dict.items(), key=lambda item: item[1])
print(sorted_dict)  # Output: [('banana', 'apple'), ('orange', 'banana'), ('apple', 'orange')]

Q5: Can I sort a dictionary by value in place, without creating a new dictionary?

A5: No, dictionaries in Python cannot be sorted in place because they are not designed to be ordered containers. The only way to sort a dictionary is to create a new ordered dictionary or a list of sorted tuples. You cannot sort the original dictionary directly.

Q6: What happens if two dictionary values are the same when sorting?

A6: When two values are the same, Python will maintain the original order of the keys for those items (since Python 3.7+, dictionaries retain insertion order). If you want to break ties by sorting based on the keys, you can specify multiple sorting criteria.

Example:

my_dict = {"apple": 5, "banana": 5, "orange": 2}
sorted_dict = sorted(my_dict.items(), key=lambda item: (item[1], item[0]))
print(sorted_dict)  # Output: [('orange', 2), ('apple', 5), ('banana', 5)]

Q7: Can I sort a dictionary with mixed types for the values (e.g., numbers and strings)?

A7: No, you cannot directly sort a dictionary if the values are of mixed types, such as both numbers and strings, because Python does not allow comparisons between incompatible types (e.g., comparing a string to an integer). You must ensure that all values are of a comparable type before sorting.

Example (Handling Mixed Types):

my_dict = {"apple": 3, "banana": "five", "orange": 2}

# Convert all values to strings or numbers for comparison
sorted_dict = sorted(my_dict.items(), key=lambda item: str(item[1]))

Q8: How can I handle sorting a dictionary with None values?

A8: If your dictionary contains None values, Python will raise a TypeError when trying to compare None with other types. To handle this, you can provide a custom sorting function that handles None values explicitly, treating them as lower or higher than other values.

Example:

my_dict = {"apple": 3, "banana": None, "orange": 2}

sorted_dict = sorted(my_dict.items(), key=lambda item: (item[1] is None, item[1]))

In this example, None values are treated as the lowest during sorting.

Q9: Is sorting by value efficient for large dictionaries?

A9: Sorting by value in large dictionaries can become inefficient because the sorted() function has a time complexity of O(n log n), where n is the number of items in the dictionary. For extremely large dictionaries, this could have a noticeable performance impact. You may want to consider optimizing your approach or limiting the number of items sorted by using techniques like partial sorting (e.g., sorting only the top N items).

Q10: Can I sort a dictionary using an external library for better performance?

A10: For most cases, Python’s built-in sorted() function is efficient enough. However, if you’re working with very large datasets and need more advanced sorting techniques, libraries like Pandas or NumPy might offer more specialized sorting methods and optimizations, especially for data frames and arrays.

Example Using Pandas:

import pandas as pd

my_dict = {"apple": 3, "banana": 5, "orange": 2}
df = pd.DataFrame(list(my_dict.items()), columns=['Key', 'Value'])
sorted_df = df.sort_values(by='Value')
print(sorted_df)

Similar Posts