Nested dictionary sum all values
I have a seemingly easy problem, but can't solve it.
Dictionary = {
'own': {
'Dun Morogh': {
'Horde': {
'chars': {
'Qiidu': {
'auction': 1
}
}
}
},
'Tirion': {
'Alliance': {
'chars': {
'Qiip': {
'auction': 1
}
}
}
},
'Proudmoore': {
'Alliance': {
'chars': {
'Qiip': {
'mail': 1
}
}
}
}
},
'name': u'Rascal-Bot'
}
This is the format I have my dictionary in and I want to loop through it, sum all the integers in it and return it.
My code:
def findTotal(self, dct):
for key, value in dct.iteritems():
if isinstance(value, int):
print key, value
if isinstance(value, dict):
self.findTotal(value)
This works on 'printing', but how would I adjust it to 'summing up'?
You can add a sum
variable to keep track of the sum, and have your function return that value. The recursive calls will add up the "sub-sums" and return them to their callers, who will add them to their totals, until you're back to the first call, and the grand total.
def findTotal(self, dct):
total = 0
for key, value in dct.iteritems():
if isinstance(value, int):
total += value
if isinstance(value, dict):
total += self.findTotal(value)
return total