Home > Mobile >  How to iterate through values of a dictionary until there is no more values (reached the end of the
How to iterate through values of a dictionary until there is no more values (reached the end of the

Time:07-07

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.

CodePudding user response:

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

CodePudding user response:

You can iterate through a dictionary with a for loop just like you would with a list, iterable, tuple, or set:

for item in d:
    print(item)

Adding up the paired items in each list that is in the dictionary is more complicated. You would have to find the length of the list, which I don't know how to do. However, if you wanted to just sum up all the items in each list (so that [2, 7, 1] becomes 10), you could do this. Using the dictionary from your question:

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

sums = [] # blank list
for list in d:
    n = 0 # used as a local variable
    for item in list:
        n  = item
    sums.append(n) # put n on the end of sums
print(sums)

Note that this is not adding the adjacent pairs in the lists, instead, it prints a list containing the sums of the lists in d. I hope my answer can help.

  • Related