将列表中的重复项合并到python字典中 [英] Merging repeated items in a list into a python dictionary

查看:333
本文介绍了将列表中的重复项合并到python字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像一个波纹管的列表,其中一对相同的项目重复了几次.

I have a list that looks like the one bellow, with the same item of a pair repeated some times.

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'])

我想将其转换为词典列表,在其中将第一项的所有重复合并到一个键中,因此最终结果将如下所示:

I would like to convert it to a list of dictionaries in which I would merge all repetitions of the first item into one key, so the end result would look like:

data = {'aaron distilled' :  ['alcohol', '5', 'gin', '2',  'beer', '6', 'vodka', '9'], 
'aaron evicted ':  ['owner', '1', 'bum', '1', 'deadbeat', '1']}

我正在尝试类似的事情:

I was trying something like:

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的新手,非常感谢任何关于如何解决此问题的技巧,或对在哪里可以找到允许我执行此操作的信息的引用.谢谢!

But I get the wrong result. I am very new to python and would really appreciate any tip on how to solve this or reference to where to find the information that would allow me to do this. Thanks!

推荐答案

使用您的第一次尝试将覆盖密钥; dict理解不会合并这些值.第二次尝试似乎将data列表中的列表视为字典,因此根本不起作用.

Your first attempty will overwrite keys; a dict comprehension would not merge the values. The second attempt seems to treat the lists in the data list as dictonaries, so that wouldn't work at all.

演示:

>>> 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字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆