-1

How can I test whether any of a or b or c are keys in a dict?

Are there some short and simple methods in Python?

With two keys, I can use

if a or b in my_dict.keys():

How can I do the same with three keys?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Yang MingHui
  • 380
  • 4
  • 14

2 Answers2

5

You may use any() to check any of the condition is True. Let say your dict is:

my_dict = {
  'x': 1,
  'y': 2,
  'a': 3   # `a` key in dict
}

In order to check any item exists in dictionary's keys, you may do:

>>> values_to_check = ['a', 'b', 'c']  # list of value to check
#                     v You do not need `.keys()` as by default `in` checks in keys 
>>> any(item in my_dict for item in values_to_check)
True
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • 1
    Or more succintly - `if my_dict.keys() & values_to_check`... (or `if my_dict.viewkeys() & values_to_check` in Python 2.x) – Jon Clements Nov 20 '16 at 13:54
1

Warning: if a or b in my_dict.keys(): doesn't do what you think. For example:

>>> 'a' or 'b' in {'c': 'd', 'e': 'f'}.keys()
'a'

What actually happens there is the result of short-circuit evaluation: first, 'a' is evaluated, and if it's "truthy", it's returned without checking anything else. Only if 'a' were "falsy" would 'b' (and only 'b') be checked against the dict's keys.

It's a little clearer what Python actually does if you add some parentheses to your code:

if (a) or (b in my_dict.keys()):

The way you'd actually have to write the two-value version of the code in that style would be:

if a in my_dict.keys() or b in my_dict.keys():
    # ...

On to your actual question:

To test an arbitrary number of values (including two), you have two choices:

if any(x in my_dict.keys() for x in (a, b, c)):
    # ...

or

if my_dict.keys() & {a, b, c}:  # replace keys with viewkeys in Python 2
    # ...

Which one of those you go for is largely down to personal taste ... although the any(...) solution is necessary if you require actual True or False results, rather than "truthy" values that work in an if statement.

Community
  • 1
  • 1
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160