字典中键的 Pythonic 简写?
简单的问题:是否有检查字典中多个键是否存在的简写?
'foo' in dct and 'bar' in dct and 'baz' in dct
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将
all()
与生成器表达式:它可以为您节省多达 2 个字符(但会为你节省很多如果您有更长的列表要检查,则更多)。
You can use
all()
with a generator expression:It saves you a whopping 2 characters (but will save you a lot more if you have a longer list to check).
则必须将 set 文字替换为
set(["foo","bar","baz"])
对于 python <2.7,如果您喜欢运算符并且不介意性能, 要创建另一个集合,您可以在该集合和字典的键集上使用
<=
运算符。两种变体组合起来看起来像:
最后,如果您使用 python 3,
dict.keys()
将返回一个 setlike 对象,这意味着您可以调用该运算符而不会造成性能损失,如下所示: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:
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: