Home > other >  Checking if any of the multiple key is in list of dicts
Checking if any of the multiple key is in list of dicts

Time:06-07

HI I need to check if any given keys is in list of dicts. Checking for a single key

  lod = [{1: "a"}, {2: "b"}, {3: "c"}, {4: "f"},{6:"x"}]
  if any(2 in d for d in lod):
     print('yes')
  else:
     print('nothing')

How about to check if any of the 2 or 4 keys?

  if any((2,4) in d for d in lod):// prints nothing
     print('yes')
  else:
     print('nothing')

CodePudding user response:

I think the comprehension way of expressing this, for an arbitrary size list of keys, would be something like:

>>> lod = [{1: "a"}, {2: "b"}, {3: "c"}, {4: "f"},{6: "x"}]
>>> any(key in d for d in lod for key in [2, 4])
True
>>> any(key in d for d in lod for key in [5, 7, 9])
False
>>> 

CodePudding user response:

You could use the or operator:

if any(2 in d or 4 in d for d in lod):
     print('yes')
else:
     print('nothing')

# yes

CodePudding user response:

Alternatively you can transform your list of dict into a ChainMap which let you treat your list of dicts as a single dict in case you don't want to combine then all into one

>>> import collections
>>> lod = [{1: "a"}, {2: "b"}, {3: "c"}, {4: "f"},{6:"x"}]
>>> chain_dict = collections.ChainMap(*lod)
>>> chain_dict
ChainMap({1: 'a'}, {2: 'b'}, {3: 'c'}, {4: 'f'}, {6: 'x'})
>>> chain_dict[3]
'c'
>>> 
>>> 2 in chain_dict
True
>>> 4 in chain_dict
True
>>> 7 in chain_dict
False

and you can use either any or all to check for multiple keys

>>> any( x in chain_dict for x in [2,4])
True
>>> any( x in chain_dict for x in [2,7])
True
>>> all( x in chain_dict for x in [2,7])
False
>>> all( x in chain_dict for x in [2,4])
True
>>> 
  • Related