Key Error creating a nested dictionary within IF statement

0

I am running a piece of code that does not present any problem to me when executing it out of the if sentence but when entering it to the sentence it throws me:

Traceback (most recent call last):
    if self.genero in self.DiccionarioReinos[self.reino][self.division][self.clase][self.orden][self.familia][self.genero]:
KeyError: 'Plantae' 

'Plantae' is being self.reino (see code below). I build the objects from an Excel. I do not understand where the error is. This is the code:

class Especie():

    DiccionarioGeneros = {}
    ListaGeneros = []
    DiccionarioFamilias = {}
    ListaFamilias = []
    DiccionarioOrdenes = {}
    DiccionarioClases = {}
    DiccionarioDivisiones = {}
    DiccionarioReinos = {}



    def __init__(self,reino,division,clase,orden,familia,genero,especie):
        self.especie = especie
        self.genero = genero
        self.familia = familia
        self.orden = orden
        self.clase = clase
        self.division = division
        self.reino = reino

    def dicGenero(self): #¿puedo usar los mismo nombres que utilice para inicializar el objeto? Si :)
        """self.DiccionarioReinos[self.reino] = {self.division:{self.clase:{self.orden:{self.familia:{self.genero:[self.especie]}}}}}
        print(self.DiccionarioReinos[self.reino][self.division][self.clase][self.orden][self.familia][self.genero])""" **#ESTO FUNCIONA DE MARAVILLA HASTA QUE LO INGRESO AL IF.**
        if self.genero in self.DiccionarioReinos[self.reino][self.division][self.clase][self.orden][self.familia]:
            self.DiccionarioReinos[self.reino][self.division][self.clase][self.orden][self.familia][self.genero].append(self.especie)
            print("ok")
        else:
            self.DiccionarioReinos[self.reino] = {self.division:{self.clase:{self.orden:{self.familia:{self.genero:[self.especie]}}}}}
            print("2")



wb = LD('ListaMMA.xlsx')
Hoja1 = wb.get_sheet_by_name('Hoja1')
UltimaFila = 25
for i in range(3, UltimaFila):
    a = "Objeto" + str(i)
    a = Especie(Hoja1.cell(row=i, column=3).value,Hoja1.cell(row=i, column=4).value,Hoja1.cell(row=i, column=5).value,Hoja1.cell(row=i, column=6).value,Hoja1.cell(row=i, column=7).value,Hoja1.cell(row=i, column=8).value,Hoja1.cell(row=i, column=9).value)
    a.dicGenero()
    
asked by Pedro Alvarez 20.02.2018 в 22:36
source

1 answer

0

I already found the problem the error is generated because it is not able to evaluate the first conditional

if self.genero in self.DiccionarioReinos[self.reino][self.division][self.clase][self.orden][self.familia][self.genero]: 

since the sentence does not exist. When the program does not exist, it falls and does not continue towards the "else" that the sentence should generate.

Greetings!

    
answered by 21.02.2018 в 03:20