PyTricks translation: How to sort a dictionary by value ( value )

This series is translated from the daily python skill improvement of the Real Python community, original translation, and reprinting is prohibited without my consent.

How to sort a Python dict by value

>>> x={'a':4,'b':3,'c':2,'d':1}
>>> sorted(x.items(),key=lambda x:x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
>>>
//或者
>>> import operator
>>> sorted(x.items(),key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
>>>

Translator's Note: dict.items() returns the key-value in the form of a traversable tuple in the form of a list, and the lambda expression takes the value of each (key, value), and then sorts.

References for unclear lambda function usage: Some special functions in Python

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324638947&siteId=291194637