SoFunction
Updated on 2024-11-20

Example of Python's dictionary sorting operation using lambda expressions

This article example describes Python using lambda expression for dictionary sorting operation. Shared for your reference, as follows:

lambda expressions are also commonly used for dictionary sorting, and since you're writing about dictionary sorting, it's good to write about both sorting by key and sorting by value.

Dictionary Key Sorting

Obviously sorting by key requires sorting by the first item of each element in the dictionary

dict = {'a':1,'b':2,'c':3,'d':4,'e':3,'f':1,'g':7}
sorted_dict_asc = sorted((),key=lambda item:item[0])
sorted_dict_dsc = sorted((),key=lambda item:item[0],reverse=True)

Output (first ascending, second descending):

[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 3), ('f', 1), ('g', 7)]
[('g', 7), ('f', 1), ('e', 3), ('d', 4), ('c', 3), ('b', 2), ('a', 1)]]

Dictionary sorted by value

Need to sort using the second term of each element in the dictionary

dict = {'a':1,'b':2,'c':3,'d':4,'e':3,'f':1,'g':7}
sorted_dict_asc = sorted((),key=lambda item:item[1])
sorted_dict_dsc = sorted((),key=lambda item:item[1],reverse=True)

exports

[('f', 1), ('a', 1), ('b', 2), ('e', 3), ('c', 3), ('d', 4), ('g', 7)]
[('g', 7), ('d', 4), ('e', 3), ('c', 3), ('b', 2), ('f', 1), ('a', 1)]

Multi-conditional sorting of dictionaries

As in the above example, we want to sort the dictionary by value and when the values are equal we sort by key, then it is multiconditional sorting.

dict = {'f':1,'b':2,'c':3,'d':4,'e':3,'a':1,'g':7}
sorted_dict_asc = sorted((),key=lambda item:(item[1],item[0]))
sorted_dict_dsc = sorted((),key=lambda item:(item[1],item[0]),reverse=True)

PS: Here is another demo tool on sorting for your reference:

Online animated demonstration of insertion/selection/bubbling/normalization/Hill/fast sort algorithm process tool:
http://tools./aideddesign/paixu_ys

Readers interested in more Python related content can check out this site's topic: thePython Data Structures and Algorithms Tutorial》、《Python list (list) manipulation techniques summarized》、《Summary of Python coding manipulation techniques》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials

I hope the description of this article will help you in Python programming.