为python嵌套字典的所有值打印完整的密钥路径 [英] Print complete key path for all the values of a python nested dictionary
问题描述
如果下面是我的嵌套字典,我想通过递归解析,并打印所有的值以及嵌套键的完整路径。
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 => Tom
_attr_types_category => employee
_attr_types_category_tag_gender => male
_attr_types_category_tag_gender_name => Tom
在上面:对于男性,关键结构不应包含category
如何保留正确关键结构?
In the above : For male, the key struct shouldnt contain "category" How to retain the correct key structure?
推荐答案
您不应该更改 pa
变量: dict_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嵌套字典的所有值打印完整的密钥路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!