开发者

Pythonic shorthand for keys in a dictionary?

Simple question: Is there a shorthand for checking the existence of 开发者_如何学JAVAseveral 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).


{"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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜