Python Forum

Full Version: call dict object result key error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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
the dict name was for the example, is not the real name, and thank for the help!