I have a dictionary like this:
{2: 3, 1: 89, 4: 5, 3: 0}
I want to reorder it so that it’s sorted by key in ascending order, resulting in:
{1: 89, 2: 3, 3: 0, 4: 5}
What’s the most straightforward or Pythonic way to sort a dictionary by key and preserve that order, especially in newer versions of Python where dictionaries maintain insertion order?
Looking for clean solutions using built-in methods or collections if needed.
Hey @Ariyaskumar, Since Python 3.7+, dictionaries keep their insertion order, so you can easily sort a dictionary by key and create a new one that stays ordered.
Here’s a clean, Pythonic way using a dictionary comprehension with sorted():
python
Copy
Edit
my_dict = {2: 3, 1: 89, 4: 5, 3: 0}
sorted_dict = {k: my_dict[k] for k in sorted(my_dict)}
print(sorted_dict)
# Output: {1: 89, 2: 3, 3: 0, 4: 5}
This sorts the keys in ascending order and rebuilds a new dict with that order preserved.
From my experience, you can also use the collections.OrderedDict if you want to be explicit about order (especially if you’re working in Python versions before 3.7):
python
Copy
Edit
from collections import OrderedDict
my_dict = {2: 3, 1: 89, 4: 5, 3: 0}
sorted_dict = OrderedDict(sorted(my_dict.items()))
print(sorted_dict)
This creates an OrderedDict sorted by keys.
But since Python 3.7+, just using a normal dict with sorted() is often simpler for python sort dictionary by key tasks.
If you want a one-liner that’s concise and does the job, try this:
python
Copy
Edit
my_dict = {2: 3, 1: 89, 4: 5, 3: 0}
sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict)
This uses dict() on the sorted list of (key, value) tuples, which preserves the key order.
It’s a very straightforward way to python sort dictionary by key without importing anything extra.
To python sort dictionary by key, use sorted() with either dictionary comprehension or directly on my_dict.items().
In modern Python, dictionaries preserve order, so this method is clean and reliable.
For older versions, OrderedDict is a solid fallback.
Let me know if you want examples for descending order or sorting by values!