How to add items to a dictionary without overwriting the previous item

Asked

Viewed 8 times

0

Greetings!!

With the code below, when instantiating an employee and then start the registration of hours worked informing the month and number of hours, inserting January:

func01 = Funcio('Joao','[email protected]') ==> ok

func01.horas_worked('January',270) ==> ok

result: dict_items([('January', {'hours': 270})])

When will I insert February:

function 01.hours_worked('February',220)

result: dict_items([('February', {'hours': 220})])

When I try to print the dictionary:

func01.imprime_meses()

result: February {'hours': 220}

That is, I understand that all months that are inserted will be recorded over the previous month. How do I record from January to December as 12 items from this dictionary?

working class:

def __init__(self, nome, email):
    self.nome = nome
    self.email = email
    
def horas_trabalhadas(self, mes , horas):
    self.mes = mes
    self.horas = horas
    self.cadastro_mes = {}
    self.cadastro_temp = {'horas' : self.horas}
    self.cadastro_mes[self.mes] = self.cadastro_temp
    print(self.cadastro_mes.items())
    
def imprime_meses(self):
    for key, value in self.cadastro_mes.items():
        print(key, value)

1 answer

0

Among other errors, you are resetting self.cadastro_mes as empty at each call of the horas_worked() method. The line

self.cadastro_mes = {}

should be moved to __init__(), that creates the class and runs only once.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.