The output must be like this:
[{'id': '1', 'first_name': 'Heidie','gender': 'Female'}, {'id': '2', 'first_name': 'Adaline', 'gender': 'Female'}, {...}
There is a code snippet that works, running this requirement.
with open('./test.csv', 'r') as file_read:
reader = csv.DictReader(file_read, skipinitialspace=True)
listDict = [{k: v for k, v in row.items()} for row in reader]
print(listDict)
However, i can't understand some points about this code above:
- List comprehension:
listDict = [{k: v for k, v in row.items()} for row in reader]
- How the python interpret this?
- How does the compiler assemble a list always with the header (
id
,first_name
,gender
) and their values? - How would be the implementation of this code with nested
for
I read theese answers, but i still do not understand:
My csv file:
id,first_name,last_name,email,gender
1,Heidie,Philimore,[email protected],Female
2,Adaline,Wapplington,[email protected],Female
3,Erin,Copland,[email protected],Female
4,Way,Buckthought,[email protected],Male
5,Adan,McComiskey,[email protected],Male
6,Kilian,Creane,[email protected],Male
7,Mandy,McManamon,[email protected],Female
8,Cherish,Futcher,[email protected],Female
9,Dave,Tosney,[email protected],Male
10,Torr,Kiebes,[email protected],Male