Explain Codes LogoExplain Codes Logo

How do I sort a dictionary by key?

python
dictionary-sorting
lambda
sortedcontainers
Alex KataevbyAlex Kataev·Aug 7, 2024
TLDR

Easily sort a dictionary by key using:

sorted_dict = dict(sorted(my_dict.items()))

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:

from collections import OrderedDict # even older Python versions like things done in an "order"ly fashion. sorted_dict = OrderedDict(sorted(my_dict.items()))

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:

# Spicing things up with vanilla values sorted_values = OrderedDict(sorted(my_dict.items(), key=lambda t: t[1])) # Sorting by length? Because size sometimes does matter. sorted_key_length = OrderedDict(sorted(my_dict.items(), key=lambda t: len(t[0])))

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():

keylist = my_dict.keys() keylist.sort() # Python's very own key sorter machine

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:

from sortedcontainers import SortedDict # It's like SortedDict always has a sorting hat on sorted_dict = SortedDict({'banana': 3, 'apple': 1, 'cherry': 2})

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:

for key, value in sorted(my_dict.items()): print(f"{key}: {value}") # Prints sorted key-value pairs, one diva at a time

Such an output format provides a line-by-line display of the sorted dictionary — quite handy when reviewing, exporting or showing off your data.