Trying to add some dictionary values

Hi im trying to add some dictionary values together and I can seem to get the context right or im doing this wrong. Would anyone mind looking to see if im doing this right as I keep doing something wrong and keep getting errors


import bge
from bge import logic
 
def add(cont):
    own = cont.owner
    if not 'init' in own:
         own["init"] = 1    
         logic.test = {"testnumber": [1, 1, 1, 1, 1, 1]}
        
    
    
    for i in range(6):
        total = sum(logic.test["testnumber"][i])
        print(total)

I want it to add the numbers together but I can seem to get it.
Thanks in advance

sum() just adds together the numbers in the list at once when you call it. So use it once like this (not sure if I’m referencing the dict properly because I havent used bge.logic for storing):


total = sum(logic.test["testnumber"])

BTW you should use globalDict instead of bge.logic to store global variables.

You’re very close. One problem I see is that you’re trying to run sum() on each individual element in a list in a for loop, rather than the list itself. The sum() function takes an iterable object, like a list, and sums up all of the elements in that iterable object. So, just supply it the list, and it will return all of the numbers within added together.

This should work:


import bge
from bge import logic
 
def add(cont):
    own = cont.owner
    if not 'init' in own:
         own["init"] = 1    
         logic.test = {"testnumber": [1, 1, 1, 1, 1, 1]}
        
    total = sum(logic.test["testnumber"])
    print(total)