Search code examples
python-3.xdictionarykeyerror

How to resolve the keyError:4?


I need to extract the rank of a specific value: This i my out_dict:

 out_dict={'198': 2, '223': 5, '102': 7, '197': 6, '183': 9, '184': 3, '248': 1, '255': 8, '179': 10, '241': 4}

This is my Key[BestByte]:

Key[BestByte]= 198

This is my code:

print (out_dict)
    for k in out_dict.values():
        if out_dict[k] == Key[BestByte]:
            print (k)

It gives me this error: KeyError: 4


Solution

  • you're looping on the values, not the keys. Loop on the keys instead. And convert to integer to compare:

    for k in out_dict:   # same as out_dict.keys(), even slightly better
        if int(k) == Key[BestByte]:
    

    BUT looping on the keys of a dictionary to test something is a dead giveaway that something could be improved:

    You're not using the dict power in that case. It would be better to do:

    if str(Key[BestByte]) in out_dict:
    

    avoids the loop, and the linear search. Now you're using the dictionary lookup with is much faster.

    In that case, now to get the value:

    if str(Key[BestByte]) in out_dict:
        value =  out_dict[str(Key[BestByte])]
    

    or just:

    value = out_dict.get(str(Key[BestByte])
    

    and test value is not None just in case the key is missing.