Python 基于多个条件对字典中的值求和

Python 基于多个条件对字典中的值求和,python,dictionary,sum,iteration,multiple-conditions,Python,Dictionary,Sum,Iteration,Multiple Conditions,我正在尝试对多个字典之间的值求和,例如: oneDic = {'A': 3, 'B': 0, 'C':1, 'D': 1, 'E': 2} otherDic = {'A': 9, 'D': 1, 'E': 15} 如果在otherDic中找到,并且如果otherDic中的相应值小于特定值,我想对oneDic中的值进行汇总 oneDic = {'A': 3, 'B': 0, 'C':1, 'D': 1, 'E': 2} otherDic = {'A': 9, 'D': 1, 'E': 15} v

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

oneDic = {'A': 3, 'B': 0, 'C':1, 'D': 1, 'E': 2}
otherDic = {'A': 9, 'D': 1, 'E': 15}
如果在
otherDic
中找到,并且如果
otherDic
中的相应值小于特定值,我想对
oneDic
中的值进行汇总

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)
oneDic={'A':3,'B':0,'C':1,'D':1,'E':2}
otherDic={'A':9'D':1'E':15}
值=12
test=sum(oneDic[value]表示键,oneDic.items()中的值表示其他测试中的计数[count]<值
返回(测试)
我希望值为4,因为在
otherDic
中找不到
C
,而
otherDic
E
的值不小于
value


但是当我运行这段代码时,我发现了一个可爱的关键错误,有人能给我指出正确的方向吗?

下面的代码片段可以工作。我不知道代码中的
count
变量是什么:

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

value = 12
test = sum(j for i,j in oneDic.items() if (i in otherDic) and (otherDic[i] < value))
print(test)
oneDic={'A':3,'B':0,'C':1,'D':1,'E':2}
otherDic={'A':9'D':1'E':15}
值=12
测试=总和(j表示i,j表示oneDic.items()如果(i表示otherDic)和(otherDic[i]<值))
打印(测试)
这个怎么样

sum(v for k, v in oneDic.items() if otherDic.get(k, value) < value)
sum(v代表k,v在oneDic.items()中,如果otherDic.get(k,value)
这里我们对oneDic的
k,v
对进行迭代,并且仅当
otherDic.get(k,value)返回时才包括它们
is
dict.get
接受两个参数,第二个参数是可选的。如果找不到键,则使用默认值。这里我们将默认值设置为
value
,以便不包括
其他DIC
中缺少的键


顺便说一下,您获得
KeyError
的原因是您试图在迭代的某个点通过执行
otherDic['B']
otherDic['C']
来访问
B和C
,这是一个
KeyError
。但是,使用
.get
就像在
otherDic.get('B')中一样
将返回默认值
None
,因为您没有提供默认值-但它不会有
KeyError

我更喜欢这个答案而不是另一个答案,因为这两个条件都是显式测试的。