[英]How to get the lowest value of second item in key list of dictionary?
Suppose we have a dictionary like this:假设我们有这样一个字典:
Dict={'2020-12-23_36.JPG': [2959, 4690],
'2020-12-28_106.JPG': [2956, 4592],
'2020-12-28_117.JPG': [2993, 4752],
'2020-12-28_13.JPG': [2919, 4921],
'2020-12-28_141.JPG': [2984, 4944]}
How do we retrieve from this the key with the lowest value of the second item in the list?:我们如何从中检索列表中第二项的最小值的键?:
import operator
min(Dict.items(), key=operator.itemgetter(1))[0]
"2020-12-28_13.JPG"
This makes sense as "2020-12-28_13.JPG" does indeed have the lowest value in the first item of the list: 2919这是有道理的,因为“2020-12-28_13.JPG”确实在列表的第一项中具有最低值:2919
I attempted the following but with no success:我尝试了以下但没有成功:
min(Dict.items(), key=operator.itemgetter(1))[1][1]
"4921"
It only prints the second item of the list, but based on the first item of the list.它仅打印列表的第二项,但基于列表的第一项。
I also tried:我也试过:
min(Dict.items(), key=operator.itemgetter(1))[1])[0]
"TypeError: 'operator.itemgetter' object is not subscriptable"
Expected result预期结果
min(Dict.items(), key=operator.itemgetter(1))[1][1]
'2020-12-28_106.JPG' #(because 4592 is the lowest value of the -1 in list)
This might actually be very simple.这实际上可能非常简单。 sorted sorts based on any "key" for any iterable.
sorted 基于任何可迭代对象的任何“键”进行排序。 In the instant case, the key is the 2nd item in the value of the dictionary.
在本例中,键是字典值中的第二项。
sorted(Dict, key = lambda x: Dict[x][1])[0]
You have small typo bug on you code, compare this:你的代码有小错别字,比较一下:
Your line你的线
min(Dict.items(), key=operator.itemgetter(1)[1])[0]
Correct one正确一个
min(Dict.items(), key=operator.itemgetter(1))[1][0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.