Pythonic shortens keys in a dictionary?

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
+5
source share
3 answers

You can use all()with generator expression :

>>> 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).

+7
source
all(x in dct for x in ('foo','bar','baz'))
+8
source
{"foo","bar","baz"}.issubset(dct.keys())

python < 2.7 set(["foo","bar","baz"])

, <= dicts.

:

set(["foo","bar","baz"]) <= set(dct)

, python 3, dict.keys() , , , :

{"foo","bar","baz"} <= dct.keys()
+5

All Articles