0

我有一本字典“celldict”,其中包含以下元素:

{1224:{'A': 6, 'B': 4, 'C': 5}, 1225: {'A': 6, 'B': 6, 'C': 5}}

我想只计算每个键的 A+B,并得到如下结果:

{1224:{'A': 6, 'B': 4, 'C': 5,'AB' : 10}, 1225: {'A': 6, 'B': 6, 'C': 5, 'AB' :12 }}

所以我这样做了:

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

但它不起作用,发现总是返回 0,当我尝试检查字典中的键是否存在时,我做错了。任何帮助将不胜感激,谢谢。

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

continue语句将跳过循环中的其余代码并开始新的迭代。没有理由在这里使用它 - 您应该删除它以便sum += celldict[num][key]实际执行该行。

您还可以更简单地编写整个内容:

for d in celldict.values():
    d['AB'] = d.get('A',0) + d.get('B',0)
于 2012-11-28T10:06:09.573 回答
0

一个简短的解决方案是:

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 回答
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

continue 后不会在 else 块中运行

于 2012-11-28T10:06:56.447 回答
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 回答