【发布时间】:2019-11-11 03:45:46
【问题描述】:
我已经编写了一个代码来将 xml 数据转换为字典列表并加载到表中。
输入文件数据:
<report>
<report_header type='comp1' title='industry' year='2019' />
<report_body age='21'>
<Prod name='krishna' id='11' place='usa'>
<License state='aus' area= 'street1'>
</License>
<License state='mus' area= 'street2'>
</License>
<License state='mukin' area= 'street3'>
</License>
</Prod>
<Prod name='ram' id='12' place='uk'>
<License state='junej' area= 'street4'>
</License>
<License state='rand' area= 'street5'>
</License>
<License state='gandhi' area= 'street6'>
</License>
</Prod>
<Prod name='chand' id='13' place='london'>
<License state='nehru' area= 'street7'>
</License>
<License state='mahatma' area= 'street8'>
</License>
<License state='park' area= 'street9'>
</License>
</Prod>
</report_body>
</report>
代码:
import xml.etree.ElementTree as ET
tree = ET.parse('sample.xml')
root = tree.getroot()
way_list=[]
for item in root.iter():
way_list.append(dict(item.attrib))
for k, v in [(k, v) for x in way_list for (k, v) in x.items()]:
print(k,v)
输出: 输入 comp1
标题行业
2019 年
21 岁
命名克里希纳
id 11
美国
澳大利亚
区域街道1
状态
区域街道2
州穆金
区域街道3
命名内存
id 12
英国
州 6 月
区域街道4
州兰特
区域街道5
甘地
区域街道6
名字陈
id 13
伦敦
国家尼赫鲁
区街7
国家大圣
区域街道8
州立公园
区域街道9
预期输出: [{type:'comp1',title:'industry',year:2019,age:21,name:'krishna',id:11,place:'usa' ,state :'aus',area:'street1'},{type:'comp1',title:'industry',year:2019,age:21,name:'krishna',id:11,place:'usa' ,state :'mus',area:'street2'},{type:'comp1',title:'industry',year:2019,age:21,name:'krishna',id:11,place:'usa' ,state :'muskin',area:'street3'},{type:'comp1',title:'industry',year:2019,age:21,name:'ram',id:12,place:'uk' ,state :'junej',area:'street4'},{type:'comp1',title:'industry',year:2019,age:21,name:'ram',id:12,place:'uk' ,state :'rand',area:'street5'},.........等]
我的主要目标是将数据加载到如下表中:
类型、标题、年份、姓名、身份证、地点、州、地区
comp1,industry,2019,krishna,11,usa,aus,street1
comp1,industry,2019,krishna,11,usa,mus,street2
comp1,industry,2019,krishna,11,usa,muskin,street3
comp1,industry,2019,ram,12,uk,junej,street4
comp1,industry,2019,ram,12,uk,rand,street5
comp1,industry,2019,ram,12,uk,gandhi,street6
现在,我可以将数据转换成字典列表了。
【问题讨论】:
标签: python python-3.x list python-2.7 dictionary