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

Sum of values from nested dictionary

I have this nested dictionary:

{'rekless': {'C': 2.0, 'H': 4.0, 'J': 0.0}, 'bwipo': {'C': 3.0, 'D': 4.0, 'H': 0.0}, 'wunder': {'D': 10.0, 'G': 20.0, 'H': 0.50}, 'caps': {'D': 3.1, 'I': 2.0, '9J': 1.0, '10K': 2.0}, 'jankos': {'D': 3.2, 'I': 2.0, 'J': 1.0, 'K': 2.0} }

Want i want to do is to loop through it and sum all values of the "C, H, J,", etc…
So like, ‘C’ is going to be (2.0 + 3.0), ‘D’ is going to be (4.0 + 10.0 + 3.1 + 3.2).

So i can end up with something similar to this:

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

{ C: 'sum of values from c', D: 'sum of values from d', etc.. }

It doesnt need to be in a dictionary the final result.

Any ideias on how to start?

>Solution :

You need to loop through both dictionary and subdictionary:

d = {
    'rekless': {'C': 2.0, 'H': 4.0, 'J': 0.0},
    'bwipo': {'C': 3.0, 'D': 4.0, 'H': 0.0},
    'wunder': {'D': 10.0, 'G': 20.0, 'H': 0.50},
    'caps': {'D': 3.1, 'I': 2.0, '9J': 1.0, '10K': 2.0},
    'jankos': {'D': 3.2, 'I': 2.0, 'J': 1.0, 'K': 2.0}
}

summary = dict()
for key, subdict in d.items():
    for k, v in subdict.items():
        summary[k] = summary.get(k, 0) + v

print(summary)
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