How do I sort a dictionary by key?
Easily sort a dictionary by key using:
This one liner leverages sorted()
on items()
, producing a dictionary with keys sorted ascendingly.
Sorting a dictionary for various Python versions
It's not all Pythonic rainbows and unicorns, different Python versions require slightly different touches.
For Python 3.6 and earlier
In the good 'ol times before Python 3.7, we used collections.OrderedDict
to keep keys in order:
Even though the OrderedDict
comes pre-sorted, it can be used just like a normal dictionary. Because it knows how to "act normal", thankfully.
Sorting with shades of lambda
When you're feeling a bit fancy and want to sort by criteria other than keys, lambda
functions got your back:
The humble lambda
functions allow a compact way to define your sorting game rules.
Python 2 and Memory Lane
Because Python 2 still lingers in some hard to reach places, you may need to get your hands dirty with keys()
:
For each key
in the nice and neat keylist
, you can then confidently pull values out of my_dict[key]
.
Dictionary sorting fine-tuning
Sometimes, your dictionary sorting calls for a little extra magi...I mean, customization. Let's delve into that.
Sorting on steroids with Sorted Containers
There's a hyperfocused module called sortedcontainers
that includes SortedDict
, keeping keys in check all the time:
The mighty SortedDict
supports index-based operations while holding keys in their sorted place.
Performance jazz
Big dictionaries call for big guns. Python’s TimSort algorithm used by sorted()
is your heavy artillery. But mind the rules of engagement:
- Less sorting, more peace.
- The complexity of your sorting key matters because, well,
lambda
. - The
sortedcontainers
module offers near-C performance, including automatic sorting!
Data presentation and readability
Making your sorted dictionary more legible is a noble cause:
Such an output format provides a line-by-line display of the sorted dictionary — quite handy when reviewing, exporting or showing off your data.
Was this article helpful?