Jym*_*son 7 python dictionary nested
从下面的嵌套字典中,我如何获得每个父字典键'value4ac'?通过启动的'value4ac'价值,我想'key4','key4a','Key4ac'.
example_dict = { 'key1' : 'value1',
'key2' : 'value2',
'key3' : { 'key3a': 'value3a' },
'key4' : { 'key4a': {
'key4aa': 'value4aa',
'key4ab': 'value4ab',
'key4ac': 'value4ac'
},
'key4b': 'value4b'
}
}
Run Code Online (Sandbox Code Playgroud)
mgi*_*son 13
救援的递归!
example_dict = { 'key1' : 'value1',
'key2' : 'value2',
'key3' : { 'key3a': 'value3a' },
'key4' : { 'key4a': { 'key4aa': 'value4aa',
'key4ab': 'value4ab',
'key4ac': 'value4ac'},
'key4b': 'value4b'}
}
def find_key(d, value):
for k,v in d.items():
if isinstance(v, dict):
p = find_key(v, value)
if p:
return [k] + p
elif v == value:
return [k]
print find_key(example_dict,'value4ac')
Run Code Online (Sandbox Code Playgroud)
这个怎么运作
它查看项目并检查2个案例
这是 @mgilson 解决方案的更广泛变体,适用于 JSON:
example_dict_with_list = { 'key1' : 'value1',
'key2' : 'value2',
'key3' : { 'key3a': 'value3a' },
'key4' : { 'key4a': [{ 'key4aa': 'value4aa',
'key4ab': 'value4ab',
'key4ac': 'value4ac'}],
'key4b': 'value4b'}
}
def breadcrumb(json_dict_or_list, value):
if json_dict_or_list == value:
return [json_dict_or_list]
elif isinstance(json_dict_or_list, dict):
for k, v in json_dict_or_list.items():
p = breadcrumb(v, value)
if p:
return [k] + p
elif isinstance(json_dict_or_list, list):
lst = json_dict_or_list
for i in range(len(lst)):
p = breadcrumb(lst[i], value)
if p:
return [str(i)] + p
print(
breadcrumb(example_dict_with_list, 'value4aa')
)
Run Code Online (Sandbox Code Playgroud)
哪个返回
['key4', 'key4a', '0', 'key4aa', 'value4aa']
Run Code Online (Sandbox Code Playgroud)
如果您需要将其很好地打印出来,例如一串面包屑,请执行以下操作
print(
' > '.join(
breadcrumb(example_dict, 'value4aa')
)
)
Run Code Online (Sandbox Code Playgroud)
哪个会返回
'key4 > key4a > 0 > key4aa > value4aa'
Run Code Online (Sandbox Code Playgroud)