简体   繁体   中英

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

Any help, tips, or advice are all appreciated. Thanks.

这很简单, 17 != '17'

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

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

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