Something strange is happening to my code that I do not understand. I have the following lines:
#informe.py
import csv
from pprint import pprint
def leer_camion(nombre_archivo):
diccionario = {}
camion = []
with open(nombre_archivo, 'rt') as f:
rows = csv.reader(f)
headers = next(rows)
for row in rows:
diccionario['nombre'] = row[0]
diccionario['cajones'] = int(row[1])
diccionario['precio'] = float(row[2])
camion.append(diccionario)
pprint(camion)
#diccionario = {}
return camion
lista = leer_camion('../Data/camion.csv')
My problem is that if I don't reset the dictionary at the end of the for
, the list is formed as follows:
[{'cajones': 100, 'nombre': 'Lima', 'precio': 32.2}]
[{'cajones': 50, 'nombre': 'Naranja', 'precio': 91.1},
{'cajones': 50, 'nombre': 'Naranja', 'precio': 91.1}]
[{'cajones': 150, 'nombre': 'Caqui', 'precio': 103.44},
{'cajones': 150, 'nombre': 'Caqui', 'precio': 103.44},
{'cajones': 150, 'nombre': 'Caqui', 'precio': 103.44}]
...
In other words, the dictionary values are rewritten both in the dictionary and in camion
, if I don't misinterpret. And the final list carries the values from the last column of the csv file. On the other hand, if I uncomment the dictionary = {}
line, that is, if I reset the dictionary at the end of the loop, the list is correctly formed:
[{'cajones': 100, 'nombre': 'Lima', 'precio': 32.2}]
[{'cajones': 100, 'nombre': 'Lima', 'precio': 32.2},
{'cajones': 50, 'nombre': 'Naranja', 'precio': 91.1}]
[{'cajones': 100, 'nombre': 'Lima', 'precio': 32.2},
{'cajones': 50, 'nombre': 'Naranja', 'precio': 91.1},
{'cajones': 150, 'nombre': 'Caqui', 'precio': 103.44}]
...
Why does this happen? Thanks a lot!