如何在我的代码中解决KeyError?

时间:2017-12-28 16:40:41

标签: python

我有以下代码:

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中不存在密钥p2ranks,对吧?

如果score2*weights[1]中尚不存在ranks[product][p2]product,我如何将值p2添加到ranks

1 个答案:

答案 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])