davidchambers
davidchambers

Reputation: 24856

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

Upvotes: 5

Views: 2372

Answers (3)

johnsyweb
johnsyweb

Reputation: 141918

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

Upvotes: 7

flying sheep
flying sheep

Reputation: 8962

{"foo","bar","baz"}.issubset(dct.keys())

For python <2.7, you’ll have to replace the set literal with set(["foo","bar","baz"])

If you like operators and don’t mind the performance of creating another set, you can use the <= operator on the set and the dict’s keyset.

Both variations combined would look like:

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

Finally, if you use python 3, dict.keys() will return a setlike object, which means that you can call the operator without performance penalty like this:

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

Upvotes: 5

unutbu
unutbu

Reputation: 880547

all(x in dct for x in ('foo','bar','baz'))

Upvotes: 8

Related Questions