如何解决Python:获取 XML 数据并放入多值字典
我有一些 XML 格式的数据需要存储在字典中。 XML 文件如下:
with open("test1.json","w") as json_file:
json.dump(jdata,json_file)
所以我需要获取数据并根据需要使用 XML ElementTree 的 Python3 脚本中的第一个子项(杂货、清洁等)对其进行排序。
最终的字典(或其他东西)应该通过保留唯一名称(Apple、Orange、Banana 等)来存储数据,如下所示:
<market>
<grocery>
<items>
<item>
<name>Apple</name>
<seller>AppleSeller</seller>
<quantity>30</quantity>
<price>10</price>
</item>
<item>
<name>Orange</name>
<seller>OrangeGuy</seller>
<quantity>25</quantity>
<price>20</price>
</item>
<item>
<name>Banana</name>
<seller>BananaMan</seller>
<quantity>35</quantity>
<price>5</price>
</item>
<item>
<name>Apple</name>
<seller>AppleSeller</seller>
<quantity>67</quantity>
<price>20</price>
</item>
</items>
</grocery>
<cleaning>
<items>
<item>
<name>Disinfectant</name>
<seller>MrClean</seller>
<quantity>24</quantity>
<price>50</price>
</item>
<item>
<name>Mop</name>
<seller>MopIndustries</seller>
<quantity>5</quantity>
<price>30</price>
</item>
</items>
</cleaning>
</market>
解决方法
您不能为字典中的所有元素创建相同的键。 检查下面的代码,它将创建所有杂货的列表。
你可以对其他元素做同样的事情
import xml.etree.ElementTree as ET
root = ET.fromstring(xmlstring)
names = [i.text for i in root.findall('grocery/items/item/name')]
seller = [i.text for i in root.findall('grocery/items/item/seller')]
quantity = [i.text for i in root.findall('grocery/items/item/quantity')]
price = [i.text for i in root.findall('grocery/items/item/price')]
ls = [list(i) for i in zip(names,seller,quantity,price)]
print(ls)
d = {"grocery": ls}
print(d)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。