Python引发了一个KeyError(对于一个out of dictionary key),即使字典中的键是IS

ign*_*lut 8 python dictionary exception key

即使我知道密钥IS实际上在字典中,我也会因为字典密钥而出现KeyError.关于可能导致这种情况的任何想法?

print G.keys()
Run Code Online (Sandbox Code Playgroud)

返回以下内容:

['24', '25', '20', '21', '22', '23', '1', '3', '2', '5', '4', '7', '6', '9', '8', '11', '10', '13', '12', '15', '14', '17', '16', '19', '18']
Run Code Online (Sandbox Code Playgroud)

但是当我尝试在下一行代码中访问字典中的值时......

for w in G[v]:    #note that in this example, v = 17
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

KeyError: 17
Run Code Online (Sandbox Code Playgroud)

任何帮助,提示或建议都表示赞赏.谢谢.

wRA*_*RAR 27

那很简单, 17 != '17'


Fog*_*ird 5

键是字符串,您尝试以int的形式访问它们.

  • @tchrist:错了.Python是强类型的...应该是.你知道,这不是PHP!(呸). (3认同)