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.
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
- Ascending vs Descending Order
- Complete Code Examples
- Alternative Approaches
- Practical Considerations
- Performance and Limitations
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 pairskey=lambda item: item[1]to extract the value for comparisondict()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)
sorted_dict = dict(sorted(your_dict.items(), key=lambda item: item[1]))
Descending Order
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:
# 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:
# 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
from operator import itemgetter
sorted_dict = dict(sorted(db_data.items(), key=itemgetter(1)))
2. Using a custom function
def get_value(item):
return item[1]
sorted_dict = dict(sorted(db_data.items(), key=get_value))
3. For complex sorting (multiple criteria)
# 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.OrderedDictfor 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:
- Use the
sorted()function withkey=lambda item: item[1]to sort by values - Control order with the
reverse=Trueparameter for descending order - Create new dictionaries from sorted items to preserve the order
- Consider performance for very large datasets
- 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
- Sort Dictionary by Value Python Descending - GeeksforGeeks
- Sort Dictionary by Value in Python – How to Sort a Dict - FreeCodeCamp
- How to Sort a Dictionary by Values in Python - DataCamp
- Python: Sort (ascending and descending) a dictionary by value - w3resource
- python - How do I sort a dictionary by value? - Stack Overflow
- python dictionary sorting in descending order based on values - Stack Overflow
- How to Sort Dictionary by Value in Python - Spark By Examples
- How to Sort a Dictionary by Key or Value in Python - Codecademy
- Sorting a Python Dictionary: Values, Keys, and More – Real Python
- Sorting a dictionary in Ascending and Descending order by Key or Value in Python - IncludeHelp