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

How to iterate through values of a dictionary until there is no more values (reached the end of the dictionary)?

Let’s say I have a dictionary such as

d = {'Item 1': [3,4,5,3], 'Item 2': [2,3,4], 'Item 3': [5,34,75,35,65]}

What I want to do is calculate the summation of two elements in the list and add them to a total. Such as for Item 1, I would want to do 3 + 4, 4 + 5, 5 + 3, and stop once I have reached the last value of the dictionary. Similarly, I want to do this with all the values in the dictionary and add them to a grand total.

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 :

If you have Python 3.10, you can use itertools.pairwise:

from itertools import pairwise, chain

d = {
    'Item 1': [3,4,5,3],
    'Item 2': [2,3,4],
    'Item 3': [5,34,75,35,65]
}

for key, numbers in d.items():
    s = sum(chain.from_iterable(pairwise(numbers)))
    print(f"{key}: {s}")

Output:

Item 1: 24
Item 2: 12
Item 3: 358

Alternatively, if you don’t have Python 3.10, you can define your own pairwise:

from itertools import tee, chain

def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    yield from zip(a, b)

If you just want a total sum:

total_sum = sum(sum(chain.from_iterable(pairwise(nums))) for nums in d.values())
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