How to resolve the keyError:4?

How to resolve the keyError:4?

我需要提取特定值的排名: 这是我的 out_dict:

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

这是我的密钥[BestByte]:

Key[BestByte]= 198

这是我的代码:

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

它给我这个错误:KeyError: 4

你循环的是值,而不是键。而是在键上循环。并转换为整数进行比较:

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

但是循环字典的键来测试某些东西是一个死的赠品,可以改进某些东西:

在这种情况下,您没有使用 dict 功能。最好这样做:

if str(Key[BestByte]) in out_dict:

避免循环,线性搜索。现在您使用的字典查找速度要快得多。

既然如此,现在获取值:

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

或者只是:

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

并测试 value is not None 以防万一钥匙丢失。

首先你的缩进看起来有点不对,for 中的所有内容都应该与上面的 print 语句的缩进相同。

至于您的问题,for k in out_dict.values() 会为您提供 out_dict 中的实际值(即 2、5、7、6 等),而不是 key词典。因此 if 逻辑将不起作用,因为 k 不是 out_dict 的键,生成你的 KeyError。有几种方法可以解决这个问题,包括:

for key, value in out_dict.items():
    if value == Key[BestByte]
        print(key)