0

So, imagine I got a dict like this:

dict = {
    "100311929821626368" : {
        "battles" : 2,
        "loses" : 0,
        "maxstamina" : 50,
        "news" : True,
        "stamina" : 50,
        "weeb" : "Chuey",
        "wins" : 0
    },
    "100802430467325952" : {
        "battles" : 4,
        "loses" : 0,
        "maxstamina" : 50,
        "news" : True,
        "stamina" : 45,
        "weeb" : "Red Haired Bastard",
        "wins" : 0
    },
    "101970309296447488" : {
        "battles" : 1,
        "loses" : 0,
        "maxstamina" : 50,
        "news" : True,
        "stamina" : 45,
        "weeb" : "Niusky",
        "wins" : 1
    }
}

and my code is this code:

wow = 0
for id in dict:
   for i in dict[id]["battles"]:
      wow += i

The problem is, I'm not sure how to add all the battles int at once. Because I get this error:

TypeError: 'int' object is not iterable

How would i fix it so it all all the battles in the dict!

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
NekoTony
  • 54
  • 8

3 Answers3

3

Is this what you want?

wow = 0
for id in dict:
     wow += dict[id]["battles"]

Explanation if necessary: dict[id]["battles"] already returns the int value. You were trying to iterate over that int which makes no sense.

Julien
  • 13,986
  • 5
  • 29
  • 53
1

This is a duplicate of this question: Iterating over dictionaries using 'for' loops

key is just a variable name.

  for key in d:

will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:

For Python 2.x:

  for key, value in d.iteritems():
        wow += value["battles"]

For Python 3.x:

  for key, value in d.items():
Community
  • 1
  • 1
Colm Seale
  • 179
  • 6
1

The problem is that dict[id]['battles'] is an object of type int, so that is the reason you are getting the error TypeError: 'int' object is not iterable.

You can solve it by:

wow = 0
for key in dict:
   wow += dict[key]['battles']

Or, you can even simplify the code by using a Python comprehension:

wow = sum(dict[key]['battles'] for key in dict)
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228