Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 call dict object result key error
#1
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
Quote
#2
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
Quote
#3
the dict name was for the example, is not the real name, and thank for the help!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  convert list of dict to dict of array of list with pop up kk230689 1 73 Sep-13-2019, 07:29 AM
Last Post: perfringo
  Error: int object does not support item assignment ankita_nthu 2 274 Jul-07-2019, 02:14 PM
Last Post: ankita_nthu
  API Call Gets 404 Error jimbone30 0 181 Jun-28-2019, 04:06 AM
Last Post: jimbone30
  call func from dict mcmxl22 3 333 Jun-21-2019, 05:20 AM
Last Post: snippsat
  Using VBA to Call a Python script causes error in pyodbc connector pcarra 1 333 Jun-11-2019, 04:14 PM
Last Post: pcarra
  Error 'object has no attribute' when iterating thru a dictionary mrapple2020 8 545 Apr-08-2019, 01:36 AM
Last Post: mrapple2020
  Getting error "Type error-a bytes-like object..." mrapple2020 1 473 Apr-06-2019, 06:37 PM
Last Post: mrapple2020
  Why doesn't gc delete an object without forcing a garbage collection call? AlekseyPython 5 475 Mar-19-2019, 02:10 AM
Last Post: micseydel
  Unexpected expected type error result MartinMaker 1 294 Feb-16-2019, 05:02 PM
Last Post: micseydel
  Why Can't I call base class function for my derived class object? AmirAB 2 324 Feb-13-2019, 03:04 PM
Last Post: snippsat

Forum Jump:


Users browsing this thread: 1 Guest(s)