【发布时间】:2017-12-02 13:12:42
【问题描述】:
我编写了一个递归函数来查找给定dict 和key 的值。
但我认为应该有一个更具可读性的版本。这是代码块。
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")
是否有任何单行版本或使用产量(不确定)?
编辑:基于 Recursive functions and lists appending/extending 和 cmets 的想法,我修改了函数以通过给定键查找所有匹配值
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'>',我敢肯定这不是您想要的。 -
第一个“if”用于检查它是否是字典类型。如果不是字典,则检查key==target,如果为true,则返回值(可以是dict以外的任何类型)
标签: python dictionary recursion