我曾经写过一个递归函数来查找给定字典和键的值。 但我认为应该有更易读的版本。以下是代码块。
def findvalue(_dict, target):
for key, values in _dict.items():
if 'dict' in str(type(values)):
return findvalue(values, target)
elif key == target:
return values
else:
print("no such key")
有没有一行代码或使用yield的版本实现这个功能?
编辑:根据递归函数和列表附加/扩展以及评论中的想法,我修改了函数以查找给定键的所有匹配值。
def find_all_value(_dict, target, values=None):
for key, values in _dict.items():
#case 1: it is a dictionary but not match the key
if isinstance(values, dict) and key!=target:
return find_all_value(values, target)
#case 2: it is a dictionary but match the key -> put it in result
elif isinstance(values, dict) and key==target:
return [values] + find_all_value(values, target)
#case 3: it is not dictionary and match the key -> put it in result
elif key==target:
return [values]
values
的str(type())
中搜索字面字符串值'dict'
。所以你基本上是在做if 'dict' in '<class 'list'>'
,我相信这不是你想要的。 - Christian Dean