昨天我學習了python。我試圖解析一個XML文件並將這些值放在字典中。如何在字典結尾添加值
xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
d ={ }
for child in root:
d[child.tag] = child.attrib
print child.tag, child.attrib
print("\n")
for k,v in d.items():
print(k,v)
現在聲明d[child.tag] = child.attrib
正在被重寫,而不是被更新。
所以我得到的輸出 -
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'}
('country', {'name': 'Panama'})
前三行輸出的是由於print()
。最後一行來自字典。
我怎樣纔能有效地做到這一點,以便我的字典存儲所有三行?
你想讓你的答案結果是什麼格式? – drewmm 2013-03-20 06:43:45
無需特定格式。任何事情都會做。我只想把所有的三個國家的價值都保存下來。 – Abhishek 2013-03-20 06:49:59