Skip to content
Advertisement

Making a dictionary from a list of lists and combining sublist[1] from repeats of sublist[0]

I have a lists of lists LofL = [['a',20], ['a',50], ['b',14], ['c', 9], ['b', 1], ['d', 44], ['d', 5]] and I want to make a dictionary that has the string as the key and the value as the values in the LofL for each respective string to be added together. EX:

dict1 = {'a': 70, 'b': 15, 'c': 9, 'd': 49}

The order doesn’t matter as I will be calling values from the dictionary if the key is equal to a different input. I’m just lost on how to have the values add together. So far all I’ve been able to make is a dictionary that has the last set of keys and values equal to what is in the dictionary. EX:

dict1 = {'a': 50, 'b': 1, 'c': 9, 'd': 44}

Advertisement

Answer

Here is another way to do so:

LofL = [['a',20], ['a',50], ['b',14], ['c', 9], ['b', 1], ['d', 44], ['d', 5]]

dict1 = {x: 0 for x, _ in LofL}
for char, num in LofL:
    dict1[char] += num
print(dict1)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement