在 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/