PinkBanter
PinkBanter

Reputation: 1976

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

I have a list of tuples

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

I want to convert this list of tuples into a dictionary in a way that values for the identical keys add up.

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

Here is the code:

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)

This is the output:

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

Upvotes: 1

Views: 594

Answers (4)

Behrooz Ostadaghaee
Behrooz Ostadaghaee

Reputation: 91

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)

Upvotes: 1

moosearch
moosearch

Reputation: 304

Try this

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

Upvotes: 1

jizhihaoSAMA
jizhihaoSAMA

Reputation: 12672

Use 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)

Upvotes: 4

Andrej Kesely
Andrej Kesely

Reputation: 195438

You can use 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))

Prints:

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

Upvotes: 1

Related Questions