考虑你有这样的字典:
{
"keys": {
"key1": {
"param1": "value1",
"param2": "value2"
},
"key2": {
"param1": "param_value1",
"param2": "param_value2"
}
}
}
您是否有任何关于如何搜索可能嵌套在某个内部dict级别的值并且返回该值的完整路径的想法。
I.E search("param_value2")
会返回类似keys/key2/param2
的内容
我想有一些库可以提供这种功能。
答案 0 :(得分:-1)
这适用于你问题中的词典
dct = {
"keys": {
"key1": {
"param1": "value1",
"param2": "value2"
},
"key2": {
"param1": "param_value1",
"param2": "param_value2"
}
}
}
def search_value(searched_value):
path = 'keys/'
for key1,value1 in dct['keys'].items():
for key2,value2 in dct['keys'][key1].items():
if value2 == searched_value:
path = 'keys/{0}/{1}'.format(key1,key2)
break
return path
print(search_value('param_value2'))
#>>>keys/key2/param2