将元组列表转换为字典并将计数信息添加为字典值

Convert a list of tuples into a dictionary and adding count information as dictionary values

我有一个元组列表

list_input = [("00", 1), ("10", 2), ("00", 3), ("10", 1), ("00", 2), ("11", 1)]

我想将这个元组列表转换为字典,使相同键的值相加。

dict_output = {'00': 6, '10': 3, '11': 1}

代码如下:

list_input = [("00", 1), ("10", 2), ("00", 3), ("10", 1), ("00", 2), ("11", 1)]
dict_output = {}
value = []
for i in range(len(list_input)):
    key = list_input[i][0]

    value.append(list_input[i][1])

    dict_output[key] = value
    print(dict_output)

这是输出:

dict_output = '00': [1, 2, 3, 1, 2, 1], '10': [1, 2, 3, 1, 2, 1], '11': [1, 2, 3, 1, 2, 1]}

您可以使用 collections.defaultdict:

from collections import defaultdict

list_input = [("00", 1), ("10", 2), ("00", 3), ("10", 1), ("00", 2), ("11", 1)]

d = defaultdict(int)
for k, v in list_input:
    d[k] += v

print(dict(d))

打印:

{'00': 6, '10': 3, '11': 1}

使用dict.get:

list_input = [("00", 1), ("10", 2), ("00", 3), ("10", 1), ("00", 2), ("11", 1)]

res = {}
for k, v in list_input:
    res[k] = res.get(k, 0) + v
print(res)

试试这个

di = {}
for t in list_input:
    key = t[0]
    value = t[1]

    # Initialize key such that you don't get key errors
    if key not in di:
        di[key] = 0

    di[key] += value
list_input = [("00", 1), ("10", 2), ("00", 3), ("10", 1), ("00", 2), ("11", 1)]

dic = {}
for key, value in list_input:
    dic[key] = dic.get(key, 0) + value
    
print(dic)