I have a list of tuples and I am expecting a dictionary where I want to count number of times the first element is repeated and sum of all the second elements.
For eg :-
input_list = [('Skills', 3), ('Wholesome', 3), ('FanArt', 3), ('Clip', 3), ('Skills', 2), ('FanArt', 2)]
Expected Output :
{"Skills": 5, "Wholesome": 3, "FanArt": 5, "Clip": 3}
I am expecting a optimised way to do this
I have tried it with simple programming with for loops. But I want to use itertools or some built in package.
You can use this
input_list = [('Skills', 3), ('Wholesome', 3), ('FanArt', 3), ('Clip', 3), ('Skills', 2), ('FanArt', 2)]
output_dict = {}
# Looping over tuple value
for k, v in input_list:
if (k in output_dict): # if key exists then add value
output_dict[k] += v
else:
output_dict[k] = v # if key not exists then key:value
print(output_dict)
You can also use the default list
from collections import defaultdict
input_list = [('Skills', 3), ('Wholesome', 3), ('FanArt', 3), ('Clip', 3), ('Skills', 2), ('FanArt', 2)]
output_dict = defaultdict(int)
for key, value in input_list:
output_dict[key] += value
print(dict(output_dict))
Counter
from collections will also work same as above
from collections import Counter
input_list = [('Skills', 3), ('Wholesome', 3), ('FanArt', 3), ('Clip', 3), ('Skills', 2), ('FanArt', 2)]
output_dict = Counter()
for key, value in input_list:
output_dict[key] += value
print(dict(output_dict))
Output
{'Skills': 5, 'Wholesome': 3, 'FanArt': 5, 'Clip': 3} # for all above code