简体   繁体   English

使用排序的Python字典排序

[英]Python Dictionary Sorting Using Sorted

This is a newbie question for which I could not find a precise answer for. 这是一个新手问题,我找不到确切的答案。 I would like to sort a dictionary in descending order according to the values. 我想根据值以降序对字典进行排序。 ie... 即...

dict = {'ann': 9, 'tom': 21, 'eddie': 12, 'fred': 5}

I know that this works... 我知道这可行...

>>> sorted(dict.items(), key=lambda x: x[1], reverse=True)
[('tom', 21), ('eddie', 12), ('ann', 9), ('fred', 5)]

But I am trying to understand how this part works... 但是我试图了解这部分是如何工作的...

x: x[1]

How is this matching the value attribute? 这如何匹配value属性?

dict.items() returns a list of (key, value) pairs, x[1] is simply the value part of that pair: dict.items()返回(key, value)对的列表, x[1]只是该对的value部分:

>>> d = {'ann': 9, 'tom': 21, 'eddie': 12, 'fred': 5}
>>> d.items()
[('ann', 9), ('fred', 5), ('eddie', 12), ('tom', 21)]
>>> d.items()[0]
('ann', 9)
>>> d.items()[0][1]
9
>>> (lambda x: x[1])(d.items()[0])
9

sorted() passes each element in the input sequence (so ('ann', 9) , etc.) into the key function. sorted()将输入序列中的每个元素(so ('ann', 9)sorted()传递到key函数中。 x is then ('ann', 9) and x[1] is 9 . x('ann', 9)x[1]9

Let me explain whats going on: 让我解释一下发生了什么:

Your dictionary: 您的字典:

d = {'ann': 9, 'tom': 21, 'eddie': 12, 'fred': 5} d = {'ann':9,'tom':21,'eddie':12,12,'fred':5}

Here is what sorted usage help says: 以下是排序的使用帮助说明:

sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

Lets break down : 让我们分解:

From your snipet: sorted(dict.items(), key=lambda x: x[1], reverse=True) 从您的片段中: sorted(dict.items(),key = lambda x:x [1],reverse = True)

iterable : d.items() 可迭代:d.items()

which is list of tuples, 

>>> d.items()
[('ann', 9), ('fred', 5), ('eddie', 12), ('tom', 21)]
>>>

key = lambda x: x[1] 键= lambda x:x [1]

NB: key parameter to specify a function to be called on each list element prior to making comparisons. NB:用于在进行比较之前在每个列表元素上指定要调用的函数的关键参数。

Lets apply to your case: 让我们适用于您的情况:

>>> key = lambda x: x[1]
>>> map(key, d.items())
[9, 5, 12, 21]
>>>

Which gave the values of the dictionary. 给出了字典的值。

reverse=True showing below, hope you can understand easily from the example. reverse = True如下所示,希望您可以从示例中轻松理解。

>>> l = [3,2,4,1]
>>> sorted(l)
[1, 2, 3, 4]
>>> sorted(l, reverse=True)
[4, 3, 2, 1]
>>>

conclusion: 结论:

You are reversing a dictionary based on value d[1] ie value and reversed it. 您正在基于值d[1]即值)反转字典并将其反转。 Final result is list of tuples ie tuple[0] = key, tuple[1] = value. 最终结果是元组列表,即tuple [0] =键,tuple [1] =值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM