0

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.

4

6 に答える 6

2

クイックジェネレータループとsum()関数を使用する方がはるかに簡単です。

sumkey = ''.join(a)
for num in celldict:
    num[sumkey] = sum(num.get(k, 0) for k in a)

このソリューションは一般的なものであり、キーを追加することができ、a引き続き機能します。

于 2012-11-28T10:08:50.507 に答える
1

The continue statement 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 the sum += celldict[num][key] line is actually executed.

You can also write this whole thing more simply:

for d in celldict.values():
    d['AB'] = d.get('A',0) + d.get('B',0)
于 2012-11-28T10:06:09.573 に答える
0
In [29]: for item in celldict:
   ....:     if celldict[item].has_key('A') and celldict[item].has_key('B'):
   ....:         celldict[item]['AB'] = celldict[item]['A'] + celldict[item]['B']
   ....:

In [30]: celldict
Out[30]:
{1224: {'A': 6, 'AB': 10, 'B': 4, 'C': 5},
 1225: {'A': 6, 'AB': 12, 'B': 6, 'C': 5}}
于 2012-11-28T10:09:39.360 に答える
0
celldict = {1224:{'A': 6, 'B': 4, 'C': 5}, 1225: {'A': 6, 'B': 4, 'C': 5}}
count_keys = ["A","B"]
counted_key = "AB"

for item in celldict.values():
    item[counted_key] = 0

    for key in count_keys:
        item[counted_key] += item[key]

print(celldict)
于 2012-11-28T10:10:18.397 に答える
0

Nothing after continue will run in the else block

于 2012-11-28T10:06:56.447 に答える
0

A short solution would be this:

def sum_keys(d, keys=["A","B"]):
    #iterate over all the dictionaries in d
    for subdict in d.values():
        #check that all required keys are in the dict
        if not all(k in subdict for k in keys): continue
        #create the sum and assign it
        subdict[''.join(keys)] = sum(subdict[k] for k in keys)
于 2012-11-28T10:08:30.503 に答える