Simple question: Is there a shorthand for checking the existence of several keys in a dictionary?
'foo' in dct and 'bar' in dct and 'baz' in dct
all(x in dct for x in ('foo','bar','baz'))
You can use all()
with a generator expression:
>>> all(x in dct for x in ('foo', 'bar', 'qux'))
False
>>> all(x in dct for x in ('foo', 'bar', 'baz'))
True
>>>
It saves you a whopping 2 characters (but will save you a lot more if you have a longer list to check).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With