【发布时间】:2016-04-22 13:32:51
【问题描述】:
如果下面是我的嵌套字典,我想递归解析并打印所有值以及嵌套键的完整路径。
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>
我写了一个递归函数,但运行到这个:
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 => 汤姆
在上面:对于男性,关键结构不应包含“类别” 如何保留正确的密钥结构?
【问题讨论】:
-
这不是代码编写或教程服务;你知道你想要一个递归函数,那么为什么不试着写一个呢?
-
编辑问题 使用minimal reproducible example
-
你离得太近了! FWIW,当你第一次学习编写递归函数时,这是一个相当常见的错误,所以希望你下次记得。 :)
标签: python dictionary nested