0

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')
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
ira
  • 534
  • 1
  • 5
  • 17
  • Why not use your list of dicts to define a _single_ dict, and then use that dict? – Pranav Hosangadi Jun 07 '22 at 01:07
  • Think carefully about the logic. What are the tests that you want to do? You want to test whether `any` particular *integer value* is `in` the keys of some dictionary, right? So, we start with `any(value in keys` (the names are arbitrary, but the point is that we expect `value` to be an integer and `keys` to be the keys of a dictionary). Now we need to do iteration that gives us the possible integer values to check, and iteration that gives us the possible dictionaries to check - since we want all possible pairings of those. So we need two `for` clauses. – Karl Knechtel Jun 07 '22 at 01:10
  • 1
    Does this answer your question? [Pythonic way of checking if a condition holds for any element of a list](https://stackoverflow.com/questions/1342601/pythonic-way-of-checking-if-a-condition-holds-for-any-element-of-a-list) – Karl Knechtel Aug 02 '22 at 23:50

3 Answers3

2

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
>>> 
cdlane
  • 40,441
  • 5
  • 32
  • 81
1

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
Onyambu
  • 67,392
  • 3
  • 24
  • 53
  • I believe that `any()` short circuits this generator expression and returns as soon as it can so I don't know that your 'better' version makes any significant improvement. – cdlane Jun 06 '22 at 23:25
0

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
>>> 
Copperfield
  • 8,131
  • 3
  • 23
  • 29