python - Python:获取 XML 数据并放入多值字典
问题描述
我有一些需要存储在字典中的 XML 数据。XML文件如下:
<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>
因此,我需要在需要使用XML ElementTree的Python3脚本中获取数据并根据第一个子项(杂货店、清洁店等)对其进行排序。
最终的字典(或其他东西)应该通过保持唯一名称(Apple、Orange、Banana 等)来存储数据,如下所示:
sorted_dictionary = {
"grocery": ["Apple", "AppleSeller", "30", "10"],
"grocery": ["Orange", "OrangeGuy", "25", "20"],
"grocery": ["Banana", "BananaMan", "35", "5"],
"cleaning": ... (same as how grocery does it)
"cleaning": ...
}
解决方案
您不能为字典中的所有元素创建相同的键。检查下面的代码,它将创建所有杂货的列表。
你可以对其他元素做同样的事情
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)
推荐阅读
- python - Python 正则表达式:计算和替换数值
- c# - 如何实现序列的约束改组
- html - 如何在绝对位置将一个元素调整为另一个元素?
- python - 使用 Python 将 Oracle BLOB 写入 CSV 时出错
- excel - 使用 VBA 名称功能重命名文件无法正常工作
- c# - 将特殊字符分配给字符串时,剃刀页面弄乱了编码
- python - Pandas:重新索引后访问时间戳属性
- php - file_get_contents(): SSL 操作失败,代码 1 - 服务器解决
- angular - 如何将管道应用于RouterLink中的值?
- c# - C# Crawler 无法加载动态内容