我试图对多个字典之间的值求和,例如:

oneDic = {'A': 3, 'B': 0, 'C':1, 'D': 1, 'E': 2}
otherDic = {'A': 9, 'D': 1, 'E': 15}


我想总结oneDic中的值,如果在otherDic中找到它们,并且otherDic中的对应值小于特定值

oneDic = {'A': 3, 'B': 0, 'C':1, 'D': 1, 'E': 2}
otherDic = {'A': 9, 'D': 1, 'E': 15}
value = 12
test = sum(oneDic[value] for key, value in oneDic.items() if count in otherTest[count] < value
return (test)


我期望值为4,因为在C中找不到otherDic,并且在EotherDic的值不小于value

但是,当我运行此代码时,我得到一个可爱的按键错误,有人可以向我指出正确的方向吗?

最佳答案

这个怎么样

sum(v for k, v in oneDic.items() if otherDic.get(k, value) < value)


在这里,我们对oneDic的k, v对进行迭代,并且仅当otherDic.get(k, value)的返回值为< value时才包括它们。 dict.get带有两个参数,第二个是可选的。如果找不到该密钥,则使用默认值。在这里,我们将默认值设置为value,以便不包括otherDic中缺少的键。

顺便说一句,得到KeyError的原因是因为您试图通过执行B and CotherDic['B']在迭代的某个时刻访问otherDic['C'],这就是KeyError。但是,在.get中使用otherDic.get('B')将返回默认的None,因为您没有提供默认值-但它将没有KeyError

关于python - 基于多个条件对字典中的值求和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29760685/

10-11 20:30