[英]How to solve KeyError in my code?
我有以下代碼段:
weights = [0.1, 0.2]
ranks = {}
for product,Rank in myDictionary1.items():
ranks[product] = {}
for p2,score2 in Rank:
p2 = int(p2)
product = int(product)
if product!=p2:
ranks[product][p2] = score2*weights[0]
for product,Rank in myDictionary2.items():
for p2,score2 in Rank:
p2 = int(p2)
product = int(product)
if product!=p2:
ranks[product][p2] = score2*weights[1]
我在代碼的這一行收到錯誤KeyError: 655
:
ranks[product][p2] = score2*weights[1]
但是,沒有關於該錯誤的其他詳細信息。
如果我正確理解該錯誤,則意味着該關鍵product
或p2
在ranks
不存在,對嗎?
如果product
或p2
尚不存在於ranks
如何將值score2*weights[1]
添加到score2*weights[1]
ranks[product][p2]
中?
您通過product = int(product)
之間的product
來更改product
ranks[product] = {}
和
ranks[product][p2] = score2*weights[0]
因此,不再保證新的整數product
將成為ranks
的關鍵。 將該轉換行一直移動到循環的開頭:
product = int(product)
ranks[product] = {}
# rest
在第二個循環中,您不采取任何措施檢查那些產品是否甚至存在於ranks
。 通常,您可以使用defaultdict
和函數來減輕生活defaultdict
,以避免重復自己的工作:
from collections import defaultdict
weights = [0.1, 0.2]
ranks = defaultdict(dict)
def process(dct, wght):
for product, Rank in dct.items():
product = int(product) # convert here
for p2, score2 in Rank:
p2 = int(p2)
if product != p2:
ranks[product][p2] = score2 * wght
process(myDictionary1, weights[0])
process(myDictionary2, weights[1])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.