简体   繁体   中英

How to solve KeyError in my code?

I have the following code piece:

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]

I get the error KeyError: 655 at this line of my code:

ranks[product][p2] = score2*weights[1]

However, there is no other detail about the error.

If I correctly understand the error, it means that the key product or p2 do not exist in ranks , right?

How can I add the value score2*weights[1] to ranks[product][p2] if product or p2 do not yet exist in ranks ?

You alter product via product = int(product) between

ranks[product] = {}

and

ranks[product][p2] = score2*weights[0]

So the new integer product is no longer guaranteed to be a key in ranks . Move that conversion line all the way up to the beginning of the loop:

product = int(product)
ranks[product] = {}
# rest

In the second loop you take no measures to check if those products are even present in ranks . Generally, you could ease your life using a defaultdict and a function in order to avoid repeating yourself:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM