Python 列表到字典:有重复的元素将充当键,但我想收集同一个键的值,并将其转换为列表值
我有以下清单:Python 列表到字典:有重复的元素将充当键,但我想收集同一个键的值,并将其转换为列表值,python,list,dictionary,Python,List,Dictionary,我有以下清单: ['Leistung', '15 kW', 'Farbe', 'Rot', 'Hersteller', 'Peugeot', 'Leistung', '25 kW', 'Hersteller', 'VW Nordamerika und Europa'] (我通过制作解析器从xml文件中获取此列表),并希望将其转换为如下所示的字典: {'Leistung': ['15 kW','25 kW'], 'Farbe': 'Rot', 'Hersteller': ['Peugeot','
['Leistung', '15 kW', 'Farbe', 'Rot', 'Hersteller', 'Peugeot', 'Leistung', '25 kW', 'Hersteller', 'VW Nordamerika und Europa']
(我通过制作解析器从xml文件中获取此列表),并希望将其转换为如下所示的字典:
{'Leistung': ['15 kW','25 kW'], 'Farbe': 'Rot', 'Hersteller': ['Peugeot','VW Nordamerika und Europa']}
我是python新手,我尝试过很多代码,但都不管用
以下是从xml文件获取列表的解析器代码:
import os
from xml.etree import ElementTree
file_name = 'data.xml'
full_file = os.path.abspath(os.path.join('data', file_name))
dom = ElementTree.parse(full_file)
autos = dom.findall('auto')
n = 6
dictionary = {}
mylist = []
for a in range(n):
for c in autos:
key = c.find('Key')
value = c.find('Value')
mylist.append(key.text)
mylist.append(value.text)
break
print(mylist)
我假设在列表中每两个项目就有一个键
l = ['Leistung', '15 kW', 'Farbe', 'Rot', 'Hersteller', 'Peugeot', 'Leistung', '25 kW', 'Hersteller', 'VW Nordamerika und Europa']
dictionnary = {}
for i in range(0, len(l) - 1, 2):
key = l[i]
if key not in dictionnary: dictionnary[key] = [l[i+1]]
else: dictionnary[key].append(l[i+1])
这对我来说是一份完美的工作 这意味着不需要索引/范围,也不需要检查键是否存在
from collections import defaultdict
lst = ['Leistung', '15 kW', 'Farbe', 'Rot', 'Hersteller', 'Peugeot', 'Leistung', '25 kW', 'Hersteller', 'VW Nordamerika und Europa']
res = defaultdict(list)
for k,v in zip(*[iter(lst)]*2):
res[k].append(v)
print(res)
产生
defaultdict(<class 'list'>, {'Leistung': ['15 kW', '25 kW'], 'Farbe': ['Rot'], 'Hersteller': ['Peugeot', 'VW Nordamerika und Europa']})
defaultdict(,{'Leistung':['15kw','25kw'],'Farbe':['Rot'],'Hersteller':['Peugeot','VW nordamerica und Europa']})
当然,根据您的描述,假设输入是成对的(键和值)
进一步说明:如果您想知道这个奇怪的拉链是做什么的,它是如何工作的,请回答您的问题吗?您是否考虑过词典中的单个项目也应该在列表中(一个元素),这样您就可以期望词典中的每个值都是一个列表?这将使与字典交互的其他代码可能更容易编写。(而且我也不认为所有的车都是红色的)这就是路!我会直接在解析器代码中使用
defaultdict
跳过中间列表级别。如果我的答案最能解决您的问题,请将其标记为已接受。很多感谢我不是OP,但我同意这应该是公认的答案。这完全有效谢谢你Pynchia这个解决方案效率低下而且多余。一点也不象蟒蛇。请花时间研究迭代协议,并使用python标准库提供的所有特性进行实验。一个很好的资源是