python - 将列表中的重复项合并到 python 字典中

标签 python list python-3.x dictionary

我有一个看起来像下面的列表,一对中的相同项目重复了几次。

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/

相关文章:

python - 在 Pandas DataFrame 中选择多个列范围

python - 生成一个列表以将 url 提供给网络抓取工具

python-3.x - 使用 python requests 模块登录网站

django - 如何在 django 中创建 2 级管理员用户,每个用户将只管理他创建的用户?

python - 如何在球体上随机散布点

python - 使用 fastText 执行示例代码时遇到问题

python - python decimal/float 中的邪恶

python - 使用关联列表对象的函数迭代列表

hibernate OneToMany 列表排序持续但反转?

python-3.x - 层标准化及其工作原理( tensorflow )