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

Chr*_*row 3 python dictionary

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

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

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
Run Code Online (Sandbox Code Playgroud)

非常感谢!

Ble*_*der 8

您可以使用all发电机:

all(key in dict_obj for key in properties_to_check_for)
Run Code Online (Sandbox Code Playgroud)

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

all(dict_obj.get(key) is not None for key in properties_to_check_for)
Run Code Online (Sandbox Code Playgroud)

d.get(key)None如果密钥不在您的字典中,它将返回,因此您不需要事先检查它是否在那里.