2015-04-21 47 views
1

我試圖總結多個詞典之間的值,例如:總結值

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,因爲CotherDic發現的EotherDic值不小於value

但是當我運行這段代碼,我得到一個可愛的關鍵錯誤,任何人可以點我在正確的方向?

回答

1

以下代碼片段起作用。我不知道在你的代碼的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) 

Link to working code

+0

我喜歡比其他答案這更好,因爲明確的被測試兩個條件。 – Marius

1

這個怎麼樣

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

在這裏,我們反覆在k, v對oneDic如果只包括其中從otherDic.get(k, value)返回的是< valuedict.get有兩個參數,第二個是可選的。如果找不到密鑰,則使用默認值。在這裏,我們將默認值設置爲value,以便不包括來自otherDic的丟失密鑰。

順便說一句,你得到的KeyError的原因是因爲你試圖做otherDic['B']otherDic['C']在迭代某個時候訪問B and C,這是一個KeyError。然而,使用.getotherDic.get('B')將返回None默認的,因爲你沒有提供一個默認的 - 但它不會有一個KeyError