Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading