在 Python 3.6 中将相同的 XML 属性组合在一起

Grouping together same XML attributes in Python 3.6

我正在使用数据库中的数据生成一个 XML 文件。 我得到的数据是这样的:

ID- 1,2,1,3

姓名- A、B、C、D

年龄- 20,25,20,20

目前正在使用以下代码:

import xml.etree.ElementTree as ET
Root=ET.Element("root")
Resultlist= <<fetching from a Database
for row in Resultlist:
  Id=ET.SubElement(Root,"ID")
  Id.set("id",str(row[1]))
  Details=ET.SubElement(Id,"Details")
  Details.set("Name",str(row[2]))
  Details.set("Age",str(row[3])

我得到的输出是

<root>
   <ID id="1">
     <Details Age="20" Name="A" />
   </ID>
   <ID id="2">
     <Details Age="25" Name="B" />
   </ID>
   <ID id="1">
      <Details Age="20" Name="C" />
   </ID>
   <ID id="3">
     <Details Age="20" Name="D" />
   </ID>
</root>

我如何修改它以获得输出,以便所有具有相同 ID 的都分组在一起?

<root>
 <ID id="1">
  <Details Age="20" Name="A" />
  <Details Age="20" Name="C" />
 </ID>
 <ID id="2">
  <Details Age="25" Name="B" />
  </ID>
 <ID id="3">
  <Details Age="20" Name="D" />
 </ID>
</root>

考虑从您的 ResultSet 构建字典,键是 ID。然后为每个不同的 ID 添加其他值的嵌套循环:

Resultlist = [(1, 1, 20, "A"), (2, 2, 25, "B"), (3, 1, 20, "C"), (4, 3, 20, "D")]

# INITIALIZE DICTIONARY OF EMBEDDED LISTS
my_dict = {row[1]:[] for row in Resultlist} 

# APPEND NESTED LISTS TO DICTIONARY
for row in Resultlist:
    my_dict[row[1]].append([row[2], row[3]])

Root = ET.Element("root")

# ITERATE THROUGH DICTIONARY
for k, v in my_dict.items():

    Id = ET.SubElement(Root, "ID")
    Id.set("id", str(k))

    for i in v:
        Details = ET.SubElement(Id, "Details")
        Details.set("Name", str(i[0]))
        Details.set("Age", str(i[1]))