简体   繁体   English

如何获取字典键列表中第二项的最低值?

[英]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.

相关问题 如何获得具有最低键值的字典 - How to get a dictionary with the lowest key value 如何更新列表中的项,它是字典中键的值? - How to update an item in a list that is value to a key in a dictionary? 如何获得成绩第二低的学生名单? - How to get the list of students with second lowest grade? 如果特定键项在字典中,如何获取列表中字典的索引 - How to get the index of a dictionary inside list if a specific key item is in the dictionary 在python中,如何获得对象/字典列表中最低的键值对,其中每个项目具有不同的,单独的键值对? - In python, how do I get the lowest key value pair in a list of objects/dicts where each item has a different, separate key value pair? 如何从列表中向字典键添加第二个值? - How to add second value to dictionary key from list? 如何从列表中的键获取字典值? - How to get dictionary value from key in a list? 如何通过第二个值将第二低的列表查找到嵌套列表中? - How to find the second lowest lists into a nested list by their second value? 如何获取字典键,其值至少包含另一个列表中的一项? - How to get dictionary key whose value contains at least one item in another list? 如何将列表转换为字典,其中第一个列表是键,第二个列表是字典中的值? - how to convert the list to dictionary where first list is key and second list is value in dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM