0

I want to check if keys are present in a dict.

There are several ways I can think of to do this:

# (1) using 'in'
if 'my_key' in my_dict.keys() and 'my_other_key' in my_dict.keys():
    ...

# (2) using set.subset
if set(('my_key', 'my_other_key')).issubset(set(my_dict.keys()))
    ...

# (3) try-except
try:
    ... # do something with my_dict['a_key'] and my_dict['my_other_key']
except KeyError:
    pass

None of these are particularly intuitive to read, especially (2) if more than a few key names need to be tested while still complying with PEP 8 line length of 80.

What I would like is something along the lines of

if my_dict.keys() contains (
        'key1',
        'key2',
        'key3'):
    ...

Is there a python idiom similar to the above, or do I need to grumble for a bit and then write a utility function?

littlebenlittle
  • 833
  • 2
  • 9
  • 18
  • define `('my_key', 'my_other_key')` as a variable and use that is `set.subset` ? – Devesh Kumar Singh Jun 05 '19 at 19:00
  • I prefer not to assign variables if they are only going to be used once. I feel like it interrupts the flow of the code to break a single logical operation info multiple statements. – littlebenlittle Jun 05 '19 at 19:03
  • well isn't that why we use variables? – Devesh Kumar Singh Jun 05 '19 at 19:04
  • 1
    You can do `{'my_key', 'my_other_key'} <= set(my_dict.keys())`. The curly braces represent a `set` and `<=` is the subset operator. I think any answer would be opinion based but many people like to follow [Ask Forgiveness, Not Permission](https://stackoverflow.com/questions/12265451/ask-forgiveness-not-permission-explain) – pault Jun 05 '19 at 19:08
  • To follow up on my previous comment, you could do `if set(my_dict.keys()) >= {'key1', 'key2', 'key3'}:` to get something along the lines of what you want, *but* `try/except` is perfectly fine as well. – pault Jun 05 '19 at 19:23

1 Answers1

4

If you are checking that they are all members, if you name your set of necessary keys set_of_keys

if all(key in my_dict.keys() for key in set_of_keys)

In fact, the way membership checks work for dictionaries, using .keys() is unnecessary. You can just check

if all(key in my_dict for key in set_of_keys)
C Haworth
  • 659
  • 3
  • 12