Print complete key path for all the values of a python nested dictionary(打印 python 嵌套字典的所有值的完整键路径)
问题描述
如果下面是我的嵌套字典,我想递归解析并打印所有值以及嵌套键的完整路径.
If below is my nested dictionary I want to parse through recursively and print all the values along with the complete path of the nested key.
my_dict = {'attr':{'types':{'tag':{'name':'Tom', 'gender':'male'},'category':'employee'}}}
预期输出:
Key structure : my_dict["attr"]["types"]["tag"]["name"]<br>
value : "Tom"<br>
Key structure : my_dict["attr"]["types"]["tag"]["gender"]<br>
value : "male"<br>
Key structure : my_dict["attr"]["types"]["category"]<br>
value : "employee"<br>
我写了一个递归函数,但是运行到这个:
I wrote a recursive function, but running to this:
my_dict = {'attr':{'types':{'tag':{'name':'Tom','gender':'male'},'category':'employee'}}}
def dict_path(path,my_dict):
for k,v in my_dict.iteritems():
if isinstance(v,dict):
path=path+"_"+k
dict_path(path,v)
else:
path=path+"_"+k
print path,"=>",v
return
dict_path("",my_dict)
输出:
_attr_types_category => 员工
_attr_types_category_tag_gender => 男性
_attr_types_category_tag_gender_name => 汤姆
_attr_types_category => employee
_attr_types_category_tag_gender => male
_attr_types_category_tag_gender_name => Tom
在上面:对于男性,关键结构不应该包含类别"如何保留正确的密钥结构?
In the above : For male, the key struct shouldnt contain "category" How to retain the correct key structure?
推荐答案
你不应该改变 dict_path()
函数中的 path
变量:
You shouldn't alter the path
variable in the dict_path()
function:
def dict_path(path,my_dict):
for k,v in my_dict.iteritems():
if isinstance(v,dict):
dict_path(path+"_"+k,v)
else:
print path+"_"+k,"=>",v
dict_path("",my_dict)
这篇关于打印 python 嵌套字典的所有值的完整键路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!