字典中键的 Pythonic 简写?

发布于 2024-11-29 14:02:56 字数 105 浏览 0 评论 0原文

简单的问题:是否有检查字典中多个键是否存在的简写?

'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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

榆西 2024-12-06 14:02:56
all(x in dct for x in ('foo','bar','baz'))
all(x in dct for x in ('foo','bar','baz'))
不气馁 2024-12-06 14:02:56

您可以将 all()生成器表达式

>>> all(x in dct for x in ('foo', 'bar', 'qux'))
False
>>> all(x in dct for x in ('foo', 'bar', 'baz'))
True
>>> 

它可以为您节省多达 2 个字符(但会为你节省很多如果您有更长的列表要检查,则更多)。

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

鲜肉鲜肉永远不皱 2024-12-06 14:02:56
{"foo","bar","baz"}.issubset(dct.keys())

则必须将 set 文字替换为 set(["foo","bar","baz"])

对于 python <2.7,如果您喜欢运算符并且不介意性能, 要创建另一个集合,您可以在该集合和字典的键集上使用 <= 运算符。

两种变体组合起来看起来像:

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

最后,如果您使用 python 3,dict.keys() 将返回一个 setlike 对象,这意味着您可以调用该运算符而不会造成性能损失,如下所示:

{"foo","bar","baz"} <= dct.keys()
{"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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文