Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic shorthand for keys in a dictionary?

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
like image 312
davidchambers Avatar asked Aug 13 '11 21:08

davidchambers


2 Answers

all(x in dct for x in ('foo','bar','baz'))
like image 167
unutbu Avatar answered Sep 30 '22 20:09

unutbu


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

like image 44
Johnsyweb Avatar answered Sep 30 '22 18:09

Johnsyweb