Dictionary key error

0

I am trying to store dictionaries in a list and then print according to the position in the list, however this is giving a key error ... 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/Alumn/AppData/Local/Programs/Python/Python36/rqwrqrqr.py",   line 18, in       print (item [name]) KeyError: 'timename'

    
asked by anonymous 08.06.2017 / 14:37

1 answer

0

When you add a dict to a list, you are adding only 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)
[{}]

By the time you run teacher.clear (), it cleans up both the teacher variable and the teachers variable, since the content points to dict itself. One solution is to insert a copy of the dict into the vector instead of the reference. To do this, use the copy() of dict method.

>>> 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'}]
    
10.06.2017 / 03:46