I have a dictionary “celldict” that has elements like these :
{1224:{'A': 6, 'B': 4, 'C': 5}, 1225: {'A': 6, 'B': 6, 'C': 5}}
I want to count just A+B for each key, and get a result like this :
{1224:{'A': 6, 'B': 4, 'C': 5,'AB' : 10}, 1225: {'A': 6, 'B': 6, 'C': 5, 'AB' :12 }}
So I did this :
a = ["A","B"]
for num in celldict :
found =0
sum = 0
for key in a :
if key in celldict[num][key]:
print "ignoring existing key"
else :
print "continuing"
continue
sum += celldict[num][key]
found = 1
if found == 1 :
celldict[num]["AB"] = sum
print celldict
But it’s not working, found always returns 0, I am doing something wrong maybe when I try to check the existence of the key in my dictionnary. Any help would be appreciated, thanks.
The
continuestatement will skip the rest of the code in the loop and start a new iteration. There is no reason to use it here – you should remove it so that thesum += celldict[num][key]line is actually executed.You can also write this whole thing more simply: