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,hphilimore0@msu.edu,Female
2,Adaline,Wapplington,awapplington1@icq.com,Female
3,Erin,Copland,ecopland2@google.co.uk,Female
4,Way,Buckthought,wbuckthought3@usa.gov,Male
5,Adan,McComiskey,amccomiskey4@theatlantic.com,Male
6,Kilian,Creane,kcreane5@hud.gov,Male
7,Mandy,McManamon,mmcmanamon6@omniture.com,Female
8,Cherish,Futcher,cfutcher7@accuweather.com,Female
9,Dave,Tosney,dtosney8@businesswire.com,Male
10,Torr,Kiebes,tkiebes9@dyndns.org,Male