[英]python - how to determine if two keys found belong to same dict from list of dicts
I have a list of dicts where I'm trying to find two keys and if found make sure they belong to the same dictionary. 我有一个字典列表,我试图在其中找到两个键,如果找到,请确保它们属于同一词典。 What I have so far: 到目前为止,我有:
foo = [{'apples': 1, 'banana': 2}, {'people': 1, 'monkeys': 2}]
food = any(d['apples'] == 1 for d in foo)
mammals = any(d['banana'] == 2 for d in foo)
if food and mammals:
return True
But how do I verify they were both from the same dictionary? 但是,如何验证它们都来自同一词典?
Just check both keys at once then there is no need for any other checks : 只需一次检查两个键,则无需进行其他任何检查:
foo = [{'apples': 1, 'banana': 4}, {'people': 1, 'monkeys': 2}]
print(any(d.get('apples') == 1 and d.get('banana')== 2 for d in f))
So simply: 如此简单:
return any(d.get('apples') == 1 and d.get('banana')== 2 for d in f)
As it stands you would actually get a keyError
, you should use dict.get
to catch when any of the keys are missing in each dict . 就目前而言,您实际上会得到一个keyError
,应该使用dict.get
来捕获每个dict中缺少任何键的时间。
Good first attempt, try this: 很好的第一次尝试,试试这个:
foo = [{'apples': 1, 'banana': 2}, {'people': 1, 'monkeys': 2}]
food = [('apples' in d and 'bannana' in d) for d in foo]
If I understand your verbal description, then the list "foo" will now contain items "True" or "False", indicating whether each dictionary contains both keys. 如果我理解您的口头描述,那么列表“ foo”现在将包含项目“ True”或“ False”,指示每个词典是否都包含两个键。 To see this is true for any dictionary in the collection, use the "any" function, as before: 要查看集合中的任何词典都是如此,请像以前一样使用“ any”函数:
contained_and_in_same_dic = any(food)
To make use of lazy evaluation, we could switch from a list to a generator and write: 为了使用惰性评估,我们可以从列表切换到生成器并编写:
contained_and_in_same_dic = any( (('apples' in d and 'bannana' in d) for d in foo) )
The plus side here is that it can break out of evaluation as soon as it finds a match, though this will only be noticeable for very large lists 有利的一面是,一旦找到匹配项,它就可以退出评估,尽管这仅在非常大的列表中才明显
Note: your solution does not match your verbal description. 注意:您的解决方案与您的口头描述不符。 The "if == 1" will raise an exception if the key is not found at all. 如果根本找不到密钥,则“ if == 1”将引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.