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 嵌套字典的所有值的完整键路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:打印 python 嵌套字典的所有值的完整键路径
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
