Python

How to sort python dictionary by key ?

Python dictionaries are not ordered by default, this example helps you to sort a python dictionary by key.

How to sort Python dictionary by key?

Even if you sort the dict using sorted() function, you wouldn’t be able to store them in another dict as because the dictionary does not preserve the order by default. Here the Python collections.OrderedDict() function helps you to preserve the order of the items.

collections.OrderedDict():

Sorting numbers.

import collections
if __name__ == '__main__':
    data = {1: 'one', 3: 'three', 4: 'four', 2: 'two'}
    print("Before sort")
    print(data)
    orderd_dict = collections.OrderedDict(sorted(data.items()))
    print("After sort")
    print(orderd_dict)

Output:

Before sort
{1: 'one', 3: 'three', 4: 'four', 2: 'two'}
After sort
OrderedDict([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])

we can even sort the sting keys using collections.orderedDict() function

import collections
if __name__ == '__main__':
    data = {'one': 1, 'three': 3, 'two': 2, 'four': 4}
    print("Before sort")
    print(data)
    orderd_dict = collections.OrderedDict(sorted(data.items()))
    print("After sort")
    print(orderd_dict)

Output:

Before sort
{'one': 1, 'three': 3, 'two': 2, 'four': 4}
After sort
OrderedDict([('four', 4), ('one', 1), ('three', 3), ('two', 2)])

Order dict key by its length:

Do you want to order the keys based on its length? yes, it can be possible by providing key as a parameter.

import collections
if __name__ == '__main__':
    data = {'one': 1, 'three': 3, 'two': 2, 'four': 4}
    print("Before sort")
    print(data)
    orderd_dict = collections.OrderedDict(sorted(data.items(), key=lambda t: len(t[0])))
    print("After sorting by key length")
    print(orderd_dict)

Output:

Before sort
{'one': 1, 'three': 3, 'two': 3, 'four': 4}
After sorting by key length
OrderedDict([('one', 1), ('two', 2), ('four', 4), ('three', 3)])

References:

Happy Learning :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Ask a question or leave a comment