Reputation: 1976
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
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
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
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
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