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?