How to Sort Dictionary by Key in Python

Python dictionaries are unordered by default. If you sort the dictionary using the sorted() method, you won’t save them in a dict in such a way that would preserve the ordering. The order will be changed.

So, the question is, is there a way to sort the dictionary by keys and preserve the ordering? Yes, it is. Let’s see how to do it.

How to sort a dictionary by Key in Python

To sort a dictionary by key in Python, use a combination of the sort() and OrderedDict() methods. The OrderedDict() is a method of the collections module that returns an instance of a dict subclass with a method specialized for rearranging dictionary order.

The sorted() function returns a sorted list of the specified iterable object. The OrderedDict() method preserves the order in which the keys are inserted.

A regular dict doesn’t track the insertion order and iterating it gives the values in an arbitrary order.

Syntax

collections.OrderedDict([items])

Parameters

The OrderedDict() method takes a dictionary as an argument.

Example

To work with OrderedDict() method, import the collections module in your file.

import collections

Now, define a dictionary using curly braces. Let’s define numbered dictionaries.

dict = {2: 21, 1: 11, 4: 46, 3: 19}

To get the keys and values of a dictionary in Python. use the dict.items() method.

To get the sorted dictionary by keys, use the combination of dict.items(), sorted(), and OrderedDict() methods.

ordered_dict = collections.OrderedDict(sorted(dict.items()))

Let’s see the complete program.

import collections

dict = {2: 21, 1: 11, 4: 46, 3: 19}

ordered_dict = collections.OrderedDict(sorted(dict.items()))

print(ordered_dict)

Output

OrderedDict([(1, 11), (2, 21), (3, 19), (4, 46)])

You can see from the output that the dictionary is ordered in ascending order.

In this example, we took numbers as keys, but we can also take characters as keys, and it will return the ordered dictionary.

import collections

dict = {"k": 21, "e": 11, "a": 46, "b": 19}

ordered_dict = collections.OrderedDict(sorted(dict.items()))

print(ordered_dict)

Output

OrderedDict([('a', 46), ('b', 19), ('e', 11), ('k', 21)])

Key-value change while ordering

If the value of a certain key is changed, the key remains unchanged in OrderedDict.

import collections

print("Before changing: \n")
odict = collections.OrderedDict()
odict['a'] = 11
odict['b'] = 19
odict['c'] = 21
odict['d'] = 46
print(odict.items())

print("After changing: \n")
odict['b'] = 18
print(odict.items())

Output

Before changing:
odict_items([('a', 11), ('b', 19), ('c', 21), ('d', 46)])

After changing:
odict_items([('a', 11), ('b', 18), ('c', 21), ('d', 46)])

The output shows that the dictionary’s order is not changed, but the value is changed from 19 to 18.

Deletion and Re-Inserting in Python Dictionary

There are so many instances where we are deleting the keys and reinserting the keys with different values in the dictionary. Deleting and re-inserting the same key will push it back as OrderedDict; it maintains the insertion order.

import collections

print("Before deleting: \n")
odict = collections.OrderedDict()
odict['a'] = 11
odict['b'] = 19
odict['c'] = 21
odict['d'] = 46
print(odict.items())

print("After deleting: \n")
odict.pop('b')
print(odict.items())

print("After re-inserting: \n")
odict['b'] = 18
print(odict.items())

Output

Before deleting:

odict_items([('a', 11), ('b', 19), ('c', 21), ('d', 46)])
After deleting:

odict_items([('a', 11), ('c', 21), ('d', 46)])
After re-inserting:

odict_items([('a', 11), ('c', 21), ('d', 46), ('b', 18)])

As you can see from the output, we used dict.pop() method to remove the key, and then we reinsert the key with value, but it will insert at the end of the dictionary.

That is it for sorting a dictionary by key in Python.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.