Home > Software design >  Sum over list in dict comprehension
Sum over list in dict comprehension

Time:10-04

I'm working on a dict comprehension. I start with a dict whose values are integer lists, and I want to transform it into a dictionary with the same keys, but with values that are the sum of the original lists. Here's a reproducible example:

n_dict = {4: [4,1,6], 3: [5,3,9], 2: [8,2,10]}
n_sum = {n_key: sum(n) for n_key in n_dict.keys() for n in n_dict[n_key]}
print(n_sum)
# expected result: {4: 11, 3: 17, 2: 20}

Unfortunately, I get the following type error, and I can't figure out why:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    n_sum = {n_key: sum(n) for n_key in n_dict.keys() for n in n_dict[n_key]}
  File "main.py", line 3, in <dictcomp>
    n_sum = {n_key: sum(n) for n_key in n_dict.keys() for n in n_dict[n_key]}
TypeError: 'int' object is not iterable

CodePudding user response:

Iterate over the items, to iterate over the key and the corresponding value at the same time:

n_dict = {4: [4, 1, 6], 3: [5, 3, 9], 2: [8, 2, 10]}
n_sum = {key: sum(value) for key, value in n_dict.items()}
print(n_sum)

Output

{4: 11, 3: 17, 2: 20}

CodePudding user response:

You do not need to loop over the items of the list and attempt to call sum for each int in the list with a nested loop.

n_dict = {4: [4,1,6], 3: [5,3,9], 2: [8,2,10]}
n_sum = {n_key: sum(n_dict[n_key]) for n_key in n_dict.keys()}
print(n_sum)
  • Related