首页 > 解决方案 > 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": ...
}

标签: pythonxmlelementtree

解决方案


您不能为字典中的所有元素创建相同的键。检查下面的代码,它将创建所有杂货的列表。

你可以对其他元素做同样的事情

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)

推荐阅读