开发者

Python raises a KeyError (for an out of dictionary key) even though the key IS in the dictionary

I'm getting a KeyError for an out of dictionary key, even though I know the key IS in fact in the dictionary. Any ideas as to what might be causing this?

print G.keys()

returns the following:

['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']

but when I try to access a value in the dictionary on the next line of code...

for w in G[v]:    #note that in this example, v = 17

I get the following error message:

KeyError: 17

A开发者_如何学编程ny help, tips, or advice are all appreciated. Thanks.


That's simple, 17 != '17'


The keys are strings, you are trying to access them as ints.


try with v = '17'. You must convert your int to string

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜