简体   繁体   English

从字典列表中提取值基于python3中的另一个值

[英]Extracting values from a list of dicts based another value in python3

I have a lists of dictionaries: 我有一个字典列表:

list = [
    {'i': 1, 'j': 1, 'diff': 39},
    {'i': 1, 'j': 1, 'diff': 27},
    {'i': 1, 'j': 1, 'diff': 18},
    {'i': 1, 'j': 1, 'diff': 33},
    ...
]

From this, I need to extract the values of i and j for the entry that has the greatest diff . 由此,我需要为diff最大的条目提取ij的值。

I've seen a lot of solutions that would simply extract the greatest diff , but that's not what's needed here. 我见过很多解决方案,它们只会提取最大的diff ,但这不是这里所需要的。 And I can think of ways to do this that would involve looping through and comparing each value to the others one by one, but that seems neither efficient nor pythonic. 而且我可以想到实现此目的的方法,该方法涉及将每个值逐个循环并与其他值进行比较,但这似乎既无效又无效。

What's the best way to go about this? 最好的方法是什么?

Use max with key argument to specify that you need to find dictionary inside list having maximum value for 'diff' key: maxkey参数一起使用以指定您需要在列表中查找具有'diff'键最大值的字典:

lst = [
    {'i': 1, 'j': 1, 'diff': 39},
    {'i': 1, 'j': 1, 'diff': 27},
    {'i': 1, 'j': 1, 'diff': 18},
    {'i': 1, 'j': 1, 'diff': 33}
]

max_dict = max(lst, key=lambda x: x['diff'])

print(max_dict['i'])  # 1
print(max_dict['j'])  # 1

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

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