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!