Error in dictionary key

Asked

Viewed 164 times

1

I am trying to store dictionaries in a list and then print according to the position in the list, however this giving an error in the key... Code below:

nome = "nomedahora"
cpf = "1421241"
departamento = "bsi"
dicProfessor = {nome: {"nome":nome, "cpf":cpf, "departamento":departamento}}
listaProfessores = []
listaProfessores.append(dicProfessor)
dicProfessor.clear()
for item in listaProfessores:
    print(item[nome])

Error:

Traceback (Most recent call last): File "C:/Users/Student/Appdata/Local/Programs/Python/Python36/rqwrqrqrqr.py", line 18, in print(item[name]) Keyerror: 'namesake'

  • Make the dicProfessor.clear() call after you finish iterating the list and not before, doing before vc will remove its reference from the list.

1 answer

3

When you add a Dict to a list, you are only adding a reference, not a copy. For example:

>>> professor = {
>>>     'nome': 'Alan Turing'
>>> }
>>> print (professor)
{'nome': 'Alan Turing'}
>>> professores = [professor]
>>> print (professores)
[{'nome': 'Alan Turing'}]
>>> professor.clear()
>>> print (professores)
[{}]

The moment you run the teacher.clear(), it cleans both the teacher variable and the teachers variable, because the content points to the same ICT. One solution is to insert a Dict copy into the vector instead of the reference. To do this, use the method copy() of Dict.

>>> professor = {
>>>     'nome': 'Alan Turing'
>>> }
>>> print (professor)
{'nome': 'Alan Turing'}
>>> # aqui fazemos uma copia, em vez de adicionar a referencia.
>>> professores = [professor.copy()]
>>> print (professores)
[{'nome': 'Alan Turing'}]
>>> professor.clear()
>>> print (professores)
[{'nome': 'Alan Turing'}]

Browser other questions tagged

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