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

Time:04-06

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}

CodePudding user response:

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)

CodePudding user response:

If you want to add all the values for a given key then I would suggest using a defaultdict as follows

from collections import defaultdict
LofL = [['a',20], ['a',50], ['b',14], ['c', 9], ['b', 1], ['d', 44], ['d', 5]]
dict1 = defaultdict(int)
for k, v in LofL:
    dict1[k]  = v

Result

>>> dict1
defaultdict(<class 'int'>, {'a': 70, 'b': 15, 'c': 9, 'd': 49})

The dict1[k] will basically allow keys to be inserted with a corresponding value of 0 on the fly, which you can use to accumulate repeated key-values as you iterate through your list of lists.

  • Related