How to Sort Dictionary in One Line Python - Simple Guide
You can sort a dictionary in one line in Python using
sorted() with a dictionary comprehension. For example, {k: v for k, v in sorted(your_dict.items())} sorts by keys, and {k: v for k, v in sorted(your_dict.items(), key=lambda item: item[1])} sorts by values.Syntax
The basic syntax to sort a dictionary in one line is:
{k: v for k, v in sorted(your_dict.items())}- sorts by keys in ascending order.{k: v for k, v in sorted(your_dict.items(), key=lambda item: item[1])}- sorts by values in ascending order.
Here, your_dict.items() gives key-value pairs, sorted() sorts them, and the dictionary comprehension rebuilds the dictionary in sorted order.
python
{k: v for k, v in sorted(your_dict.items())}
{k: v for k, v in sorted(your_dict.items(), key=lambda item: item[1])}Example
This example shows how to sort a dictionary by keys and by values in one line each.
python
your_dict = {'apple': 3, 'banana': 1, 'cherry': 2}
# Sort by keys
sorted_by_keys = {k: v for k, v in sorted(your_dict.items())}
# Sort by values
sorted_by_values = {k: v for k, v in sorted(your_dict.items(), key=lambda item: item[1])}
print('Sorted by keys:', sorted_by_keys)
print('Sorted by values:', sorted_by_values)Output
Sorted by keys: {'apple': 3, 'banana': 1, 'cherry': 2}
Sorted by values: {'banana': 1, 'cherry': 2, 'apple': 3}
Common Pitfalls
Common mistakes include:
- Trying to sort the dictionary directly without using
items(), which causes errors. - Not using a key function when sorting by values, so sorting defaults to keys.
- Expecting the original dictionary to change; sorting creates a new dictionary.
python
wrong = dict(sorted(your_dict.items())) # This is correct # Correct way: correct = {k: v for k, v in sorted(your_dict.items())}
Quick Reference
| Operation | One-line Code |
|---|---|
| Sort by keys ascending | {k: v for k, v in sorted(your_dict.items())} |
| Sort by values ascending | {k: v for k, v in sorted(your_dict.items(), key=lambda item: item[1])} |
| Sort by keys descending | {k: v for k, v in sorted(your_dict.items(), reverse=True)} |
| Sort by values descending | {k: v for k, v in sorted(your_dict.items(), key=lambda item: item[1], reverse=True)} |
Key Takeaways
Use sorted() with your_dict.items() to sort dictionaries in one line.
Add a key function like lambda item: item[1] to sort by values instead of keys.
Dictionary comprehensions rebuild the sorted dictionary in the desired order.
Sorting creates a new dictionary; the original dictionary stays unchanged.
Use reverse=True in sorted() to sort in descending order.