【发布时间】:2020-11-17 11:17:02
【问题描述】:
我有以下 xml 文件,其中包含重复的 groupId。我想把它转换成一个接受这个多个 ID 的字典。
到目前为止,当我尝试将列表转换为字典时,它消除了所有键(但最后一个键)。
所以我想把我的字典转换成一个列表。 有什么帮助吗?
XML 是:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.5.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.3.2.GA</version>
</dependency>
代码
depend = root.xpath("//*[local-name()='dependency']")
dependencyInfo = defaultdict(dict)
for dep in depend:
infoList = []
self.counter += 1
for child in dep.getchildren():
infoList.append(child.tag.split('}')[1])
infoList.append(child.text)
dependencyInfo[infoList[1]].update({infoList[2] : infoList[3],infoList[4] : infoList[5]})
输出
defaultdict(<class 'list'>, {'junit': [{'artifactId': 'junit', 'version': '3.8.1'}], 'org.hibernate': [{'artifactId': 'hibernate-core', 'version': '3.6.3.Final'}})
预期输出:
defaultdict(<class 'list'>, {'junit': [{'artifactId': 'junit', 'version': '3.8.1'}], 'org.hibernate': [{'artifactId': 'hibernate-core', 'version': '3.6.3.Final'}, 'org.hibernate': [{'artifactId': 'hibernate', 'version': '3.2.5.ga'}, 'org.hibernate': [{'artifactId': 'hibernate-entitymanager', 'version': '3.3.2.GA'}})
根据我的研究,字典不能有重复的值,所以我需要把它放在一个列表或集合中。
【问题讨论】:
-
您能否举例说明最终字典
dependencyInfo的外观? -
更新@Daniser
-
预期的输出多次包含键
org.hibernate(因为 XML 中的groupId多次包含相同的文本)。您应该为最终输出考虑不同的结构(列表和字典的层次结构)。
标签: python list dictionary set