Python 中的字典元素是否有干净的测试?
Is there a clean test for a dictionary element in Python?
如果我有一个元素,我想从字典中获取:
my_dict[i]['level_1']['level_2']['my_var']
.
有没有比这样做更简洁的方法来检查空值?
if 'level_1' in my_dict[i]:
if 'level_2' in my_dict[i]['level_1']:
if 'my_var' in my_dict[i]['level_1']['level_2']:
my_var = my_dict[i]['level_1']['level_2']['my_var']
您可以简单地定义自己的:
def get_deep(dic,*keys,default=None):
for key in keys:
if isinstance(dic,dict) and key in dic:
dic = dic[key]
else:
return default
return dic
或者如果你想测试:
def in_deep(dic,*keys):
for key in keys:
if isinstance(dic,dict) and key in dic:
dic = dic[key]
else:
return False
return True
您可以将此代码与 in_deep(my_dict[i],'level1','level2','my_var')
一起使用,如果它确实可以深入字典,它将 return True
。如果你想获得那么深的元素,你可以调用get_deep(my_dict[i],'level1','level2','my_var')
。 get_deep
将 return default
参数(默认情况下 None
)以防无法到达路径。
这是我的单行本:
# returns False or the value of the end element
reduce(lambda x, y: x and y in x and x[y], list_of_keys, target_dictionary)
示例:
a = {'b': {'c': {'d': True}}}
reduce(lambda x, y: x and y in x and x[y], ['b', 'c', 'd'], a) # True
reduce(lambda x, y: x and y in x and x[y], ['b', 'cd', 'd'], a) # False
工作原理:在每次 reduce 迭代中,它都会检查目标字典中是否存在先前的键 (x
)。如果不是,它将立即 return False because of and
condition 并将其传播到列表中。然后,它将检查请求的密钥是否在字典中 (x in y
)。如果是,它会将下层字典作为x
.
传递给下层
注意:最后一个元素 (a['b']['c']['d']) 的计算结果必须为 True。如果您期望最后出现 False,请明确检查最后一级:'d' in reduce(...)
如果我有一个元素,我想从字典中获取:
my_dict[i]['level_1']['level_2']['my_var']
.
有没有比这样做更简洁的方法来检查空值?
if 'level_1' in my_dict[i]:
if 'level_2' in my_dict[i]['level_1']:
if 'my_var' in my_dict[i]['level_1']['level_2']:
my_var = my_dict[i]['level_1']['level_2']['my_var']
您可以简单地定义自己的:
def get_deep(dic,*keys,default=None):
for key in keys:
if isinstance(dic,dict) and key in dic:
dic = dic[key]
else:
return default
return dic
或者如果你想测试:
def in_deep(dic,*keys):
for key in keys:
if isinstance(dic,dict) and key in dic:
dic = dic[key]
else:
return False
return True
您可以将此代码与 in_deep(my_dict[i],'level1','level2','my_var')
一起使用,如果它确实可以深入字典,它将 return True
。如果你想获得那么深的元素,你可以调用get_deep(my_dict[i],'level1','level2','my_var')
。 get_deep
将 return default
参数(默认情况下 None
)以防无法到达路径。
这是我的单行本:
# returns False or the value of the end element
reduce(lambda x, y: x and y in x and x[y], list_of_keys, target_dictionary)
示例:
a = {'b': {'c': {'d': True}}}
reduce(lambda x, y: x and y in x and x[y], ['b', 'c', 'd'], a) # True
reduce(lambda x, y: x and y in x and x[y], ['b', 'cd', 'd'], a) # False
工作原理:在每次 reduce 迭代中,它都会检查目标字典中是否存在先前的键 (x
)。如果不是,它将立即 return False because of and
condition 并将其传播到列表中。然后,它将检查请求的密钥是否在字典中 (x in y
)。如果是,它会将下层字典作为x
.
注意:最后一个元素 (a['b']['c']['d']) 的计算结果必须为 True。如果您期望最后出现 False,请明确检查最后一级:'d' in reduce(...)