【发布时间】:2013-12-01 20:54:36
【问题描述】:
我有一个看起来像下面这样的列表,其中相同的项目重复了几次。
l = (['aaron distilled ', 'alcohol', '5'],
['aaron distilled ', 'gin', '2'],
['aaron distilled ', 'beer', '6'],
['aaron distilled ', 'vodka', '9'],
['aaron evicted ', 'owner', '1'],
['aaron evicted ', 'bum', '1'],
['aaron evicted ', 'deadbeat', '1'])
我想将其转换为字典列表,在其中我会将第一项的所有重复项合并到一个键中,因此最终结果如下所示:
data = {'aaron distilled' : ['alcohol', '5', 'gin', '2', 'beer', '6', 'vodka', '9'],
'aaron evicted ': ['owner', '1', 'bum', '1', 'deadbeat', '1']}
我正在尝试类似:
result = {}
for row in data:
key = row[0]
result = {row[0]: row[1:] for row in data}
或
for dicts in data:
for key, value in dicts.items():
new_dict.setdefault(key,[]).extend(value)
但我得到了错误的结果。我对 python 非常陌生,非常感谢有关如何解决此问题的任何提示或参考在哪里可以找到允许我执行此操作的信息。谢谢!
【问题讨论】:
标签: python list python-3.x dictionary