我有一个字典“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,我做错了也许当我试图检查我的词典中是否存在密钥时。任何帮助将不胜感激,谢谢。
答案 0 :(得分:2)
使用快速生成器循环和sum()
函数:
sumkey = ''.join(a)
for num in celldict:
num[sumkey] = sum(num.get(k, 0) for k in a)
此解决方案是通用的,您可以向a
添加额外的密钥,它将继续有效。
答案 1 :(得分:1)
continue
语句将跳过循环中的其余代码并开始新的迭代。这里没有理由使用它 - 您应该将其删除,以便sum += celldict[num][key]
行实际执行。
你也可以更简单地写下这整篇文章:
for d in celldict.values():
d['AB'] = d.get('A',0) + d.get('B',0)
答案 2 :(得分:0)
继续之后的任何内容都将在else块中运行
答案 3 :(得分: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)
答案 4 :(得分: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}}
答案 5 :(得分: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)