How to sort a python dictionary by keys

I am a fan of hash tables when I need to implement logic that augments computation results to a common data structure that need to be used across several function bodies. The ability of the hash table in providing constant access by key helps me in keeping my logic from taking too much time to complete.

Python's version of hash tables are known as a dictionaries or associative arrays. Apart from augmenting computation results to values of my Python dictionaries, one common task that I often perform is sorting the results by the dictionary keys. In this post, I document how I can sort my Python dictionary by its keys.

Python example code to sort a dictionary by keys

user_dict = {
    10: {'name': 'Mary', 'age': 32},
    1: {'name': 'John', 'age': 15},
    2: {'name': 'Oliver', 'age': 21}
}

for key in sorted(user_dict.keys()):
    print(str(key) + ': ' + str(user_dict[key]))

The above code first defines a dictionary of dictionaries with integers as keys. We then utilise the sorted function to get the keys of user_dict in sorted order and feed the sorted keys into a for loop. In each iteration, we then use the key to access the corresponding dictionary and print both the key and the dictionary which it references to standard output.

Running the code will produce the following output:

1: {'age': 15, 'name': 'John'}
2: {'age': 21, 'name': 'Oliver'}
10: {'age': 32, 'name': 'Mary'}

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.