如何从元组列表中聚合值并将其存储在字典中?

时间:2019-01-11 15:33:00

标签: python python-3.x list dictionary tuples

输入:

list = [("a",1),("b",2),("c",3),("a",4),("b",5),("c",6)]

这是我正在寻找的输出:

d = {"a":5,"b":7,"c":9}    

3 个答案:

答案 0 :(得分:1)

遍历列表;作为元组,第一个对象[0]是您的字母,第二个[1]是数字。它尝试添加数字。如果尚未创建密钥(第一次看到字母),它将创建密钥。

d = {}
list = [("a",1),("b",2),("c",3),("a",4),("b",5),("c",6)]



for i in list:
    try:
        d[i[0]] += i[1]
    except KeyError:
        d[i[0]] = i[1]


print(d)

输出:

{'a': 5, 'b': 7, 'c': 9}

答案 1 :(得分:1)

您可以使用collections.defaultdict和一个循环:

from collections import defaultdict

lst = [('a', 1), ('b', 2), ('c', 3), ('a', 4), ('b', 5), ('c', 6)]
d = defaultdict(int)

for item in lst:
    d[item[0]] += item[1]

print(dict(d))  # {'a': 5, 'b': 7, 'c': 9}

请注意,请勿为变量list命名,以免用相同的名称遮盖built-in function

答案 2 :(得分:0)

没有依赖性的替代方法

res_ = {}
for e in mlist:
  if e[0] in res_: res_[e[0]] += e[1]
  else: res_[e[0]] = e[1]

print(res_)
#=> {'a': 5, 'c': 9, 'b': 7}