我有以下代码:
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
,对吧?
如果score2*weights[1]
中尚不存在ranks[product][p2]
或product
,我如何将值p2
添加到ranks
?
答案 0 :(得分:9)
您在
之间通过product
更改product = int(product)
ranks[product] = {}
和
ranks[product][p2] = score2*weights[0]
因此,product
不再保证新的整数ranks
成为关键字。将该转换线一直移动到循环的开头:
product = int(product)
ranks[product] = {}
# rest
在第二个循环中,您无需检查ranks
中是否存在这些产品。通常,您可以使用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])