1
a = dict()
uid1 = 1
uid2 = 2
a[uid1] = {}
a[uid2] = {}
iid1 = 45
iid2 = 98
iid3 = 3
iid4 = 82
iid5 = 11
a[uid1][iid1] = 125
a[uid2][iid2] = 7
a[uid1][iid3] = 4
a[uid2][iid4] = 10
a[uid2][iid5] = 20

get a:

{1: {45: 125, 3: 4}, 2: {98: 7, 82: 10, 11: 20}}

What I want to get is to calculate the sum of 125+4=129 and 7+10+20=37

I've tried this:

for u,items in a.items():
    for i,counts in items.items():
        for count in counts:
            print(count)

got a notice like this:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-48-8b6a2dace81e> in <module>
      1 for u,items in a.items():
      2     for i,counts in items.items():
----> 3         for count in counts:
      4             print(count)

TypeError: 'int' object is not iterable

Now I don't know how to proceed.

nucsit026
  • 652
  • 7
  • 16
bulala
  • 45
  • 1
  • 7
  • By the time you're at the second for loop, `counts` is already the numbers you want (125, 4, etc). – Justin Jan 30 '20 at 04:47
  • Does this answer your question? [Get key by value in dictionary](https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary) – prashant Jan 30 '20 at 05:05

3 Answers3

0

You're really close

for u,items in a.items():
    print(sum(items.values()))

129
37

Explanation

Your error occurs on your counts.values() call. For each iteration of your first loop, items is a dictionary.

for u, items in a.items():
    print(items)

{45: 125, 3: 4}
{98: 7, 82: 10, 11: 20}

You can see what counts is with your next loop

for u,items in a.items():
    for i, count in items.items():
        print(count)

125
4
7
10
20

count is an integer. If you wanted to keep your two loop structure, you could do

for u,items in a.items():
    sum = 0
    for i, count in items.items():
        sum += count
    print(sum)

129
37
Damian Vu
  • 389
  • 2
  • 6
  • 11
0

Its simple, try with single line.

a = {1: {45: 125, 3: 4}, 2: {98: 7, 82: 10, 11: 20}}
print([sum(values.values()) for key,values in a.items()])
Saisiva A
  • 595
  • 6
  • 24
-1

Here is how you can calculate your result:

result = [sum(dct.values()) for dct in a.values()]
print(result) # [129, 37]

Problem in your code is next:

for u,items in a.items():
    for i,counts in items.items():
        print(counts) # it prints 125, 4, 7, 10, 20

In your code you trying to iterate counts which is int number

alex2007v
  • 1,230
  • 8
  • 12