python - 如何测试字典是否包含某些键

标签 python dictionary

是否有一种很好的方法来测试字典是否包含多个键?

一个简短的版本:

d = {}
if 'a' in d and 'b' in d and 'c' in d:
    pass #do something

谢谢。

编辑:我只能用python2.4 -.-

最佳答案

你可以使用set.issubset(...),像这样:

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> set(['a', 'b']).issubset(d)
True
>>> set(['a', 'x']).issubset(d)
False

Python 3 引入了一组文字语法,该语法已向后移植到 Python 2.7,因此现在可以编写上面的内容:

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> {'a', 'b'}.issubset(d)
True
>>> {'a', 'x'}.issubset(d)
False

关于python - 如何测试字典是否包含某些键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3415347/

相关文章:

python - 难以比较生成的和谷歌云存储提供的 CRC32c 校验和

Swift Annotation 字幕高度和宽度

c++ - 显示 `std::map`

python - PyCharm - 尾部类型提示和线宽限制

python - Bokeh 相当于 matplotlib subplots

python - 在 tensorflow 中沿任何轴归一化意味着什么?

python - python 中的 glob 函数,带有一个通配符

python-3.x - 打印在 map 中时不打印,Python

Python查找文件中的最后一次出现

python - 如何使用 sqlalchemy 将数据加载到现有数据库表中?