NeuroAgent

How to Sort Dictionary by Value in Python

Learn how to sort Python dictionaries by value in ascending or descending order. Complete guide with code examples for efficient dictionary sorting in Python.

Question

How do I sort a dictionary by value?

I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.

I can sort on the keys, but how can I sort based on the values?

Note: I have read a Stack Overflow question about sorting a list of dictionaries by value, and I could change my code to use a list of dictionaries. However, since I don’t really need a list of dictionaries, I’m looking for a simpler solution to sort the dictionary by value in either ascending or descending order.

NeuroAgent

To sort a Python dictionary by value, you can use the sorted() function with a lambda function to extract the values, then create a new dictionary from the sorted items. For ascending order: sorted_dict = dict(sorted(your_dict.items(), key=lambda item: item[1])). For descending order: sorted_dict = dict(sorted(your_dict.items(), key=lambda item: item[1], reverse=True)).


Contents


Basic Sorting Method

The primary method for sorting a dictionary by value involves using Python’s built-in sorted() function with a custom key parameter. Since dictionaries maintain insertion order in Python 3.7+, you can create a new sorted dictionary.

The basic approach uses:

  • dictionary.items() to get key-value pairs
  • key=lambda item: item[1] to extract the value for comparison
  • dict() to convert back to a dictionary

This method works for both numeric and string values, automatically handling comparison appropriately.

Important: In Python 3.7+, dictionaries preserve insertion order, so the sorted order will be maintained when you create a new dictionary from the sorted items.

Ascending vs Descending Order

The key difference between ascending and descending order sorting is the reverse parameter:

Ascending Order (Default)

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

Descending Order

python
sorted_dict = dict(sorted(your_dict.items(), key=lambda item: item[1], reverse=True))

As the FreeCodeCamp article explains: “If you don’t set reverse at all or you set its value to false, the dictionary will be arranged in ascending order. That’s the default.”

Complete Code Examples

Let’s create a comprehensive example with your database field scenario:

python
# Sample dictionary based on your database fields
db_data = {
    "user_001": 45,
    "user_002": 23,
    "user_003": 67,
    "user_004": 12,
    "user_005": 89
}

# Sort by value in ascending order
sorted_ascending = dict(sorted(db_data.items(), key=lambda item: item[1]))
print("Ascending order:", sorted_ascending)

# Sort by value in descending order
sorted_descending = dict(sorted(db_data.items(), key=lambda item: item[1], reverse=True))
print("Descending order:", sorted_descending)

Output:

Ascending order: {'user_004': 12, 'user_002': 23, 'user_001': 45, 'user_003': 67, 'user_005': 89}
Descending order: {'user_005': 89, 'user_003': 67, 'user_001': 45, 'user_002': 23, 'user_004': 12}

Handling Different Value Types

The same approach works for various value types:

python
# String values
string_dict = {"apple": "fruit", "carrot": "vegetable", "beef": "meat"}
sorted_strings = dict(sorted(string_dict.items(), key=lambda item: item[1]))

# Mixed numeric types
mixed_dict = {"a": 3.14, "b": 42, "c": 1}
sorted_mixed = dict(sorted(mixed_dict.items(), key=lambda item: item[1]))

As DataCamp notes: “The sorted() function will sort the values alphabetically in ascending or descending order, just as it does with numbers.”

Alternative Approaches

While the lambda function approach is most common, here are some alternatives:

1. Using operator.itemgetter

python
from operator import itemgetter

sorted_dict = dict(sorted(db_data.items(), key=itemgetter(1)))

2. Using a custom function

python
def get_value(item):
    return item[1]

sorted_dict = dict(sorted(db_data.items(), key=get_value))

3. For complex sorting (multiple criteria)

python
# If you need to sort by value first, then by key for ties
sorted_dict = dict(sorted(db_data.items(), key=lambda item: (item[1], item[0])))

The Stack Overflow discussion confirms that these approaches work well, with the lambda method being particularly popular for its readability.

Practical Considerations

Memory Efficiency

  • Creating a new dictionary doubles memory usage temporarily
  • For very large dictionaries, consider iterating directly rather than creating a new dictionary

Performance

  • Sorting has time complexity of O(n log n)
  • For small to medium dictionaries, this is perfectly acceptable
  • The Real Python guide emphasizes that this approach is efficient for most use cases

Dictionary Immutability

  • Dictionaries remain unchanged (original dict is not modified)
  • You always get a new sorted dictionary

Performance and Limitations

Time Complexity

The sorting operation has O(n log n) time complexity, which is optimal for comparison-based sorting. This is efficient for most practical purposes.

Memory Usage

  • Creates temporary list of tuples during sorting
  • Final dictionary creation uses additional memory
  • For extremely large dictionaries, consider alternative approaches

Python Version Compatibility

  • Works in Python 3.7+ (where dict preserves order)
  • In Python 3.6 and earlier, order preservation is implementation detail
  • Alternative: Use collections.OrderedDict for guaranteed order preservation

As the GeeksforGeeks article explains, this approach is “high to low” for descending order and maintains the sorted structure in the resulting dictionary.


Conclusion

To effectively sort a dictionary by value in Python:

  1. Use the sorted() function with key=lambda item: item[1] to sort by values
  2. Control order with the reverse=True parameter for descending order
  3. Create new dictionaries from sorted items to preserve the order
  4. Consider performance for very large datasets
  5. Handle different value types appropriately (numeric, strings, etc.)

This approach gives you the flexibility to sort your database-derived dictionary by values while maintaining clean, readable code. The solution is both efficient and straightforward, avoiding the need to convert to list of dictionaries as mentioned in your original question.

For further exploration, you might want to experiment with custom sorting keys for more complex scenarios, such as sorting by multiple criteria or handling special cases in your data.

Sources

  1. Sort Dictionary by Value Python Descending - GeeksforGeeks
  2. Sort Dictionary by Value in Python – How to Sort a Dict - FreeCodeCamp
  3. How to Sort a Dictionary by Values in Python - DataCamp
  4. Python: Sort (ascending and descending) a dictionary by value - w3resource
  5. python - How do I sort a dictionary by value? - Stack Overflow
  6. python dictionary sorting in descending order based on values - Stack Overflow
  7. How to Sort Dictionary by Value in Python - Spark By Examples
  8. How to Sort a Dictionary by Key or Value in Python - Codecademy
  9. Sorting a Python Dictionary: Values, Keys, and More – Real Python
  10. Sorting a dictionary in Ascending and Descending order by Key or Value in Python - IncludeHelp