如何在保留冗余值的同时将元组列表转换为字典? [英] How do I turn a list of tuples into a dictionary while keeping redundant values?

查看:49
本文介绍了如何在保留冗余值的同时将元组列表转换为字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在获取一个格式化为键-值对列表的数据集.键是数据源,值是数据元素.例如:

I'm getting a data set that's formatted as a list of key-value pairs. The key is the data source, and the value is the data element. For example:

[('a', 3), ('b', 5), ('a', 7), ('c', 15), ('d', 12)]

我想将此列表变成字典.我可以使用Python的内置 dict(),但是它会丢弃冗余值,并且仅保留与给定键关联的最后一个值.我希望将冗余值放入列表,如下所示:

I want to turn this list into a dictionary. I could use Python's built-in dict(), but it throws away redundant values and keeps only the last value associated with a given key. I would like redundant values to go into a list, as follows:

{'a': [3, 7],
'b': [5],
'c': [15],
'd': [12]}

有没有一种简单的方法可以完成上述操作?我认为一定有,但是我似乎无法通过Google找到正确的提示.

Is there a simple way to do the above? I think there has to be, but I can't seem to find the right hint via Google.

推荐答案

collections 模块中的 dict 子类 defaultdict 可用于首次访问时,会自动为每个键初始化一个新的 list .

The dict subclass defaultdict in the collections module can be used to automatically initialize a new list for each key the first time you access it.

有了它,您只需要遍历输入对并将每个值附加到相应键的 list 上,以生成所需的值列表.

With it, you just need to loop through the input pairs and append each value to the list of the corresponding key in order to produce the lists of values you want.

import collections    

data = [('a', 3), ('b', 5), ('a', 7), ('c', 15), ('d', 12)]
result = collections.defaultdict(list)

for key, value in data:
    result[key].append(value)

print result

defaultdict(<type 'list'>, {'a': [3, 7], 'c': [15], 'b': [5], 'd': [12]})

print result['a']

[3, 7]

print result['z']

[]

这篇关于如何在保留冗余值的同时将元组列表转换为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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