Python Forum

Full Version: KeyError: '1'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone, I am receiving an error:
Error:
Traceback (most recent call last): File "C:\Users\RoszkowskiM\Desktop\win5.py", line 120, in <module> busses_in_year = mydict[Year] KeyError: '1'
I am assuming it has something to do with my dictionary. The goal of this code is to match year and data_location and it will output 3 sets of data. The data is coming from a csv sheet.

data = list(csv.reader(open(LOAD_GEN_DATAFILE)))for row in data:
    mydict = {}
    Year,busnum,busname,scaled_power,tla,data_location,empty,year_link,from_,to,digit,name2,tla_2,min_value,max_value = row[0:15]
    

    busses_in_year = mydict[Year]
    #Add the bus to the list of busses that stop at this location
    busses_in_year[data_location].append((busnum,busname,scaled_power))

    if Year in mydict and data_location in mydict[Year]:  
        busses_in_year = mydict[Year]
        print("Here are all the busses at that location for that year and the new LOAD TOTAL: ")
        print("\n")
    
    
        output='Bus #: {}\t Area Station: {}\t New Load Total: {} MW\t'
        print(output.format(busnum,busname,scaled_power))
            

    else:
        exit
In line 6, mydict is empty, as defined on line 2. So anything you try to pull out of there is going to give you a key error. You need to assign something to mydict['1'] before you can access anything from it.