Home > OS >  Check for multiple kv in a dictonary with a twist
Check for multiple kv in a dictonary with a twist

Time:03-29

I have a search list of dicts that I need to check if exist in another source dict.

source_dict = { 'a':'1', 'blue':'yes', 'c':'3' } 

search_list = [ {'a':'1', 'b':'2'}, {'blue': 'yes'} ]

The items in the list all need to be checked however, we need a AND for all items in the same dict. OR between dicts in the list.

How would I start to tackle this problem?

CodePudding user response:

You can use any and all:

>>> # the `OR` (`any`) of the `AND`s (`all`s) for each dict
>>> any(all(k in source_dict and source_dict[k] == v for k, v in d.items()) for d in search_list)
True
>>> # the `AND`s (`all`s) for each dict
>>> [all(k in source_dict and source_dict[k] == v for k, v in d.items()) for d in search_list]
[False, True]

CodePudding user response:

from functools import reduce
reduce(lambda a,b: all(a) or all(b),
    map(lambda x: map(lambda k: source_dict[k] == x[k] if k in source_dict else False, x.keys()),
    search_list))
  • Related