Python Use lambda Expression to Sort Dictionary Operation Example

  • 2021-07-26 08:25:51
  • OfStack

In this paper, the example shows that Python uses lambda expression to sort dictionaries. Share it for your reference, as follows:

lambda expressions are also commonly used in dictionary sorting. Since dictionary sorting is written, both key sorting and value sorting are written.

Dictionary key sorting

Obviously, the key sorting needs to be sorted 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(dict.items(),key=lambda item:item[0])
sorted_dict_dsc = sorted(dict.items(),key=lambda item:item[0],reverse=True)

Output (1st ascending order, 2nd descending order):

[('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)]]

Dictionaries are sorted by value

You need to use the second item of each element in the dictionary for sorting


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

Output

[('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. When the values are equal, we press the key to sort, which is multi-conditional sorting.


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

PS: Here we recommend another demonstration tool about sorting for your reference:

Online animation demonstrates insert/select/bubble/merge/hill/quick sort algorithm process tool:
http://tools.ofstack.com/aideddesign/paixu_ys

More readers interested in Python can check the topics of this site: "Python Data Structure and Algorithm Tutorial", "Python List (list) Operation Skills Summary", "Python Coding Operation Skills Summary", "Python Function Use Skills Summary", "Python String Operation Skills Summary" and "Python Introduction and Advanced Classic Tutorial"

I hope this article is helpful to everyone's Python programming.


Related articles: