I'm doing an exercise that asks me to create a program that reads a text file and transforms each line of it into a dictionary, among other things. The problem is that once I run the code, only the last line of the file appears as a dictionary.
Exercise:
The text file will be called people.txt and will have the following content in plain text (create it previously):
1;Carlos;Pérez;05/01/1989
2;Manuel;Heredia;26/12/1973
3;Rosa;Campos;12/06/1961
4;David;García;25/07/2006
The dictionary fields will be in order:
id
,nombre
,apellido
andnacimiento
.
#Vamos a transformar cada linea del fichero en un diccionario:
d = {}
with open("personas.txt") as fichero:
for linea in fichero:
(val1,val2,val3,val4) = linea.split(";")
d["id"] = val1
d["nombre"] = val2
d["apellido"] = val3
d["nacimiento"] = val4
print(d)
The screen output of the code is as follows:
{'id': '4', 'nombre': 'David', 'apellido': 'García', 'nacimiento': '25/07/2006'}
The problem can be interpreted in two ways:
Dictionary of lists
You create a dictionary where each entry is a list of the values across all the people.
In this code it is implemented by initializing the dictionary with empty lists and adding the data of a person in each iteration:
produces:
list of dictionaries
A list where each element is a dictionary corresponding to a particular person.
In this case we start with an empty list and in each iteration we create a dictionary, adding it to the list.
produces: