gpt4 book ai didi

python - 在 python 的字典树中搜索值

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:14:50 25 4
gpt4 key购买 nike

我有一个巨大的字典,里面有很多嵌套的字典——就像一棵大树,深度未知。

我需要一个函数,比如 find_value(),它接受字典,值(作为字符串),并返回列表列表 ,它们中的每一个都是“路径”(从第一个键到具有找到值的键(或键值)的键的顺序链)。如果没有找到,返回空列表。

我写了这段代码:

def find_value(dict, sought_value, current_path, result):   
for key,value in dict.items():
current_path.pop()
current_path.append(key)
if sought_value in key:
result.append(current_path)
if type(value) == type(''):
if sought_value in value:
result.append(current_path+[value])
else:
current_path.append(key)
result = find_value(value, sought_value, current_path, result)
current_path.pop()
return result

我调用这个函数来测试:

result = find_value(self.dump, sought_value, ['START_KEY_FOR_DELETE'], [])
if not len(result):
print "forgive me, mylord, i'm afraid we didn't find him.."
elif len(result) == 1:
print "bless gods, for all that we have one match, mylord!"

由于一些莫名其妙的原因,我对这个函数的实现在我的一些测试中失败了。我开始调试并发现,即使 current_path 打印出正确的东西(它总是正确的,我检查过!),结果莫名其妙地损坏了。也许是因为递归魔法?

谁能帮我解决这个问题?也许我的任务有一个简单的解决方案?

最佳答案

当您编写 result.append(current_path) 时,您并不是在复制 current_path,它会继续变异。将其更改为 result.append(current_path[:])

关于python - 在 python 的字典树中搜索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16287763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com