我有一个看起来像下面的列表,一对中的相同项目重复了几次。
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 的新手,非常感谢有关如何解决此问题的任何提示或引用在哪里可以找到允许我执行此操作的信息。谢谢!
最佳答案
使用 collections.defaultdict()
object为了方便:
from collections import defaultdict
result = defaultdict(list)
for key, *values in data:
result[key].extend(values)
您的第一次尝试将覆盖 key ;字典理解不会合并这些值。第二次尝试似乎将 data
列表中的列表视为字典,所以这根本行不通。
演示:
>>> from collections import defaultdict
>>> data = (['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'])
>>> result = defaultdict(list)
>>> for key, *values in data:
... result[key].extend(values)
...
>>> result
defaultdict(<class 'list'>, {'aaron distilled ': ['alcohol', '5', 'gin', '2', 'beer', '6', 'vodka', '9'], 'aaron evicted ': ['owner', '1', 'bum', '1', 'deadbeat', '1']})
关于python - 将列表中的重复项合并到 python 字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20052327/