python - 检查 Python 中的 dict 对象中是否存在属性集合

标签 python dictionary

在 Python 中检查字典对象中是否存在属性集合的好方法是什么?

目前我们正在这样做,但似乎有更好的方法:

properties_to_check_for = ['name', 'date', 'birth']
for property in properties_to_check_for:
    if property not in dict_obj or dict_obj[property] is None:
        return False

非常感谢!

最佳答案

您可以将 all 与生成器一起使用:

all(key in dict_obj for key in properties_to_check_for)

它会短路,就像您的 for 循环一样。这是您当前代码的直接翻译:

all(dict_obj.get(key) is not None for key in properties_to_check_for)

d.get(key) 将返回 None 如果键不在你的字典中,所以你真的不需要事先检查它是否在里面.

关于python - 检查 Python 中的 dict 对象中是否存在属性集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16878574/

相关文章:

python - 元组到字符串,每个元素都有一个函数

python - 无法安装dask[完成]

python - 如何屏蔽 DICOM 图像?

python - 根据第一列值将数据拆分为多个矩阵

Java - 不可修改的键集映射

python - HTTPError : Bad Request with urllib. request.urlopen python 的问题

c# - 绑定(bind)自定义类中的键

xcode - 快速计算字典中字典的数量

python - 使用嵌套字典创建多索引 `Series`

python - 以编程方式在 Vagrant 中获取 vm 的 IP 地址