A 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
You can use all()with generator expression :
all()
>>> all(x in dct for x in ('foo', 'bar', 'qux')) False >>> all(x in dct for x in ('foo', 'bar', 'baz')) True >>>
This saves you as much as 2 characters (but it saves you a lot more if you have a longer list to check).
all(x in dct for x in ('foo','bar','baz'))
{"foo","bar","baz"}.issubset(dct.keys())
python < 2.7 set(["foo","bar","baz"])
set(["foo","bar","baz"])
, <= dicts.
<=
:
set(["foo","bar","baz"]) <= set(dct)
, python 3, dict.keys() , , , :
dict.keys()
{"foo","bar","baz"} <= dct.keys()