🐶
Python

Sort Python Dictionary by Value

By Filip on 10/05/2024

Learn different methods with Python code examples to efficiently sort dictionaries by value and tailor the sorting order to your needs.

Sort Python Dictionary by Value

Table of Contents

Introduction

In Python, you can't directly sort a dictionary because they are inherently unordered. However, you can easily create a sorted representation of the dictionary. Here are two common methods to achieve this:

Step-by-Step Guide

You can't directly sort a Python dictionary because dictionaries are inherently unordered. Instead, you create a sorted representation of the dictionary. Here's how:

  1. Use sorted() and items():

    • Get a list of key-value pairs from the dictionary using dictionary.items().
    • Use the sorted() function on this list.
    • sorted() accepts a key argument to specify how to sort. To sort by values, use a lambda function: lambda item: item[1].
    my_dict = {'apple': 3, 'banana': 1, 'cherry': 2}
    sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
    print(sorted_dict)  # Output: {'banana': 1, 'cherry': 2, 'apple': 3}
  2. For reverse sorting:

    • Add reverse=True to the sorted() function.
    sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
    print(sorted_dict)  # Output: {'apple': 3, 'cherry': 2, 'banana': 1} 

Explanation:

  • dictionary.items(): Returns a view object containing tuples of (key, value) pairs.
  • sorted(iterable, key, reverse): Sorts an iterable.
    • key: Specifies a function to extract the sorting criteria.
    • reverse: If True, sorts in descending order.
  • lambda item: item[1]: An anonymous function that takes a (key, value) pair (item) and returns the value (item[1]) for sorting.
  • dict(): Converts the sorted list of tuples back into a dictionary.

Important Notes:

  • This process creates a new sorted dictionary, leaving the original dictionary unchanged.
  • If you need to frequently sort the dictionary or maintain a sorted order, consider using collections.OrderedDict. It remembers the order in which items were inserted.

Code Example

The Python code demonstrates sorting a dictionary by its values. It first defines a sample dictionary with fruits as keys and their quantities as values. Then, it sorts the dictionary in ascending and descending order based on the values using the "sorted" function and a lambda expression to specify the sorting key. Finally, it prints both sorted dictionaries.

# Example of sorting a Python dictionary

my_dict = {'apple': 3, 'banana': 1, 'cherry': 2}

# Sort by values in ascending order
sorted_dict_asc = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print("Sorted in ascending order:", sorted_dict_asc) 
# Output: Sorted in ascending order: {'banana': 1, 'cherry': 2, 'apple': 3}

# Sort by values in descending order
sorted_dict_desc = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
print("Sorted in descending order:", sorted_dict_desc)
# Output: Sorted in descending order: {'apple': 3, 'cherry': 2, 'banana': 1} 

Explanation:

  1. my_dict = {'apple': 3, 'banana': 1, 'cherry': 2}: Creates a sample dictionary.
  2. sorted_dict_asc = dict(sorted(my_dict.items(), key=lambda item: item[1])):
    • my_dict.items(): Gets the key-value pairs as a list of tuples: [('apple', 3), ('banana', 1), ('cherry', 2)].
    • sorted(...): Sorts this list. The key=lambda item: item[1] tells it to sort based on the second element (the value) of each tuple.
    • dict(...): Converts the sorted list of tuples back into a dictionary.
  3. print("Sorted in ascending order:", sorted_dict_asc): Prints the sorted dictionary.
  4. sorted_dict_desc = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True)): This does the same as above but sorts in descending order using reverse=True.
  5. print("Sorted in descending order:", sorted_dict_desc): Prints the sorted dictionary in descending order.

Additional Notes

  • Sorting by keys: While the examples focus on sorting by values, you can easily sort by keys by changing the lambda function to lambda item: item[0].
  • Stability: Python's sorting algorithm is stable. This means if two items have the same value, their order in the sorted output will be the same as their order in the original dictionary.
  • Alternatives to lambda: You can use a regular named function instead of a lambda function for the key argument if you prefer. This can improve readability for more complex sorting logic.
  • Performance: Creating a new sorted dictionary has a time complexity of O(n log n) due to the sorting operation. If you need to perform many lookups on the sorted data, consider using collections.OrderedDict for better performance.
  • Dictionaries vs. Other Data Structures: If you need your data to be inherently ordered or require frequent sorting, consider using lists of tuples [(key1, value1), (key2, value2), ...] or collections.OrderedDict instead of a regular dictionary.
  • Python Versions: The methods described here work in both Python 3 and recent versions of Python 2.7.

Summary

While you can't directly sort a Python dictionary due to its unordered nature, you can easily create a sorted representation. Here's the breakdown:

Method:

  1. Extract key-value pairs: Use dictionary.items() to get a list of tuples.
  2. Sort the list: Apply the sorted() function to this list.
  3. Define sorting criteria: Utilize a lambda function within sorted() to specify sorting by value: key=lambda item: item[1].
  4. Reverse the order (optional): Add reverse=True to sorted() for descending order.
  5. Convert back to dictionary: Use dict() to transform the sorted list back into a dictionary.

Example:

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

Key Points:

  • This creates a new sorted dictionary, leaving the original untouched.
  • For persistent sorting, consider collections.OrderedDict which remembers insertion order.

Conclusion

Understanding how to create sorted representations of dictionaries is crucial for working with data in Python. By using the sorted() function with a custom key, you can easily obtain a sorted version of your dictionary based on either keys or values. Remember that this process generates a new dictionary, preserving the original. For scenarios demanding frequent sorting or inherent order, consider utilizing collections.OrderedDict. By mastering these techniques, you'll be well-equipped to effectively manage and manipulate dictionary data in your Python projects.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait