【发布时间】:2017-12-27 02:03:53
【问题描述】:
我遇到了在嵌套 python 字典和列表中查找目标值路径的问题。 例如,我有以下 dict,我的目标值为“blah blah blah”。
{ "id" : "abcde",
"key1" : "blah",
"key2" : "blah blah",
"nestedlist" : [
{ "id" : "qwerty",
"nestednestedlist" : [
{ "id" : "xyz",
"keyA" : "blah blah blah" },
{ "id" : "fghi",
"keyZ" : "blah blah blah" }],
"anothernestednestedlist" : [
{ "id" : "asdf",
"keyQ" : "blah blah" },
{ "id" : "yuiop",
"keyW" : "blah" }] } ] }
我想得到的是这个值在嵌套字典和列表中的路径。 “nestedlist” - “nestednestedlist” - “keyA”
我从Find all occurrences of a key in nested python dictionaries and lists 找到了这段代码 并进行了一些更改:
def find(key,dic_name):
if isinstance(dic_name, dict):
for k,v in dic_name.items():
if k == 'name' and v == key:
yield v
elif isinstance(v,dict):
for result in find(key,v):
yield result
elif isinstance(v,list):
for d in v:
for result in find(key,d):
yield result
但它只能在结果中获取目标值,而不能获取路径。 任何人都可以帮忙吗?非常感谢
【问题讨论】:
标签: python list dictionary nested