【发布时间】:2022-01-15 19:14:55
【问题描述】:
我有一个带有嵌套字典和一个特定数字的函数(在我编写的代码中等于 1) 我需要编写一个遍历字典并仅返回映射到等于特定选择数字的键的值的递归函数 这是我写的
def nested_get(d, key):
res=[]
for i in d.keys():
if i == key:
res.append(d[i])
return res
if type(d[i]) is dict:
another = nested_get(d[i], key)
if another is not None:
return res + another
return []
print(nested_get({1:{1:"c",2:"b"},2:"b"},1))
我需要它返回 ['c'] 但它返回 [{1:'c',2:'b'}]
【问题讨论】:
-
交换 if 的。检查之前是dict
-
你没有返回 None - 删除最后一个 return [] 或检查空列表
-
缩进错误
标签: python dictionary recursion