How to sort the output of a Python dictionary

Dictionaries in Python are inherently unordered, but can be sorted and displayed using the following methods:

  1. Utilize the sorted() function: Sort the keys of a dictionary using the sorted() function, then iterate through the sorted keys to output the key-value pairs in the order of the sorted keys.
my_dict = {'b': 2, 'a': 1, 'c': 3}
sorted_keys = sorted(my_dict)
for key in sorted_keys:
    print(key, my_dict[key])
  1. Using the sorted() function and lambda expression: specify sorting rules with a lambda expression to convert the key-value pairs of a dictionary into tuples, then sort and output using the sorted() function.
my_dict = {'b': 2, 'a': 1, 'c': 3}
sorted_items = sorted(my_dict.items(), key=lambda x: x[0])
for key, value in sorted_items:
    print(key, value)
  1. Using the OrderedDict class from the collections module: The OrderedDict class is a dictionary that maintains the order in which items were inserted, allowing for key-value pairs to be output in that same order.
from collections import OrderedDict

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

The above method allows you to choose the sorting method that suits your needs to output the content of the dictionary.

bannerAds