Python Forum
call dict object result key error - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: call dict object result key error (/thread-18367.html)



call dict object result key error - lateublegende - May-14-2019

hello, my program include a dict, but when I try to call a object of the dict, that result with a KeyEror
actualsearch=0
dict={ 0: 41, 1: 41, 2: 41, }

if dict[int(actualsearch)]==41: #I try int and str, but both dosen't work
    do something
    actualsearch=actualsearch+1
I want to call the dict object whit the var actualsearch, but they call this error
Error:
if dict[int(actualsearch)]==41: KeyError: '0'
if you can help my, I will be thankful


RE: call dict object result key error - buran - May-14-2019

Actually, your code works as it is now. The KeyError '0' , i.e. - the key is str shown suggest you tried with
if dict[str(actualsearch)]==41:
actualsearch=0
dict={0:41, 1:41, 2:41}
 
if dict[int(actualsearch)]==41: #I try int and str, but both dosen't work
    actualsearch=actualsearch+1
    print(actualsearch)
output
Output:
1
several other things

1. don't use dict as variable name, it's a built-in function and you override it
2. actualsearch is int, the keys in the dict are also int. there is no need of any conversion
3. it's good to use dict.get() method to avoid KeyError if key is missing
actual_search = 0
my_dict = {0:41, 1:41, 2:41}
 
if my_dict.get(actual_search) == 41:
    # do something
    actual_search += 1



RE: call dict object result key error - lateublegende - May-15-2019

the dict name was for the example, is not the real name, and thank for the help!