简体   繁体   中英

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 .

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. To see this is true for any dictionary in the collection, use the "any" function, as before:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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