在嵌套的python字典中找到目标值的路径并列出

编程入门 行业动态 更新时间:2024-10-25 18:34:08
本文介绍了在嵌套的python字典中找到目标值的路径并列出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个问题,需要在嵌套的python字典和列表中找到目标值的路径. 例如,我遵循以下格言,而我的目标值是等等等等".

I have an issue of finding the path of the targeted values in a nested python dictionary and list. for example, I have following dict, and my targeted value is "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" }] } ] }

我要获取的是此值在嵌套字典和列表中的路径. 嵌套列表"-嵌套列表"-"keyA"

What I want to get is the path of this value in the nested dictionary and list. "nestedlist" - "nestednestedlist" - "keyA"

我从中找到了此代码>在嵌套的python字典和列表中查找所有出现的键 并进行了一些更改:

I found this code from Find all occurrences of a key in nested python dictionaries and lists and made some changes:

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

但是它只能在结果中获取目标值,而不能在路径中获取. 有人可以帮忙吗?非常感谢

But it can only get the targeted value in the result but not the path. Can anyone help? Thanks a lot

推荐答案

您链接到的代码的微小变化就会产生结果:

a minor change of the code you link to yields the results:

def fun(dct, value, path=()): for key, val in dct.items(): if val == value: yield path + (key, ) for key, lst in dct.items(): if isinstance(lst, list): for item in lst: for pth in fun(item, value, path + (key, )): yield pth

供您输入:

for item in fun(dct, value='blah blah blah'): print(item) # ('nestedlist', 'nestednestedlist', 'keyA') # ('nestedlist', 'nestednestedlist', 'keyZ')

在评论后进行更新:对代码进行较小的更改即可完成您想要的操作:

update after your comment: a minor change of the code can do what you want:

def fun(dct, value, path=()): for key, val in dct.items(): if val == value: yield path + (val, ) for key, lst in dct.items(): if isinstance(lst, list): for item in lst: for pth in fun(item, value, path + (dct['id'], key, )): yield pth

示例:

for item in fun(dct, value='xyz'): print(item) # ('abcde', 'nestedlist', 'qwerty', 'nestednestedlist', 'xyz')

更多推荐

在嵌套的python字典中找到目标值的路径并列出

本文发布于:2023-11-30 12:02:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649879.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:目标值   嵌套   字典   路径   中找到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!