SoFunction
Updated on 2025-03-04

Implementation of python dictionary sorting according to key

In Python, dictionaries are unordered and do not support sorting by keys directly. However, the dictionary can be sorted by keys by the following methods:

Method 1: Use the sorted() function and the items() method of the dictionary

my_dict = {'b': 2, 'c': 3, 'a': 1}
sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[0])}
print(sorted_dict)

This method uses the sorted() function to sort the list of key values ​​returned by the items() method of the dictionary, and then recreate an ordered dictionary using the dictionary derivation.

Method 2: Use Class

from collections import OrderedDict
 
my_dict = {'b': 2, 'c': 3, 'a': 1}
sorted_dict = OrderedDict(sorted(my_dict.items(), key=lambda item: item[0]))
print(sorted_dict)

This method uses the OrderedDict class in the collections module to construct an ordered dictionary by passing in the key-value pair list sorted by the sorted() function.

Method 3: Use the itemgetter() function of the operator module

import operator
 
my_dict = {'b': 2, 'c': 3, 'a': 1}
sorted_dict = dict(sorted(my_dict.items(), key=(0)))
print(sorted_dict)

This method uses the itemgetter() function of the operator module as a key parameter to the sorted() function, and then sorts it and then builds an ordered dictionary.

This is the end of this article about the implementation of python dictionary sorting based on keys. For more related python dictionary key sorting content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!