-1

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:

  1. 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
Joao Albuquerque
  • 366
  • 1
  • 3
  • 15

1 Answers1

1

your list comprehension :

listDict = [{k: v for k, v in row.items()} for row in reader]

equals:

item_list = []

#go through every row
for row in reader:
    item_dict = {}
    #in every row go through each item
    for k,v in row.items():
        #add each items k,v to dict.
        item_dict[k] = v
    #append every item_dict to item_list
    item_list.append(item_dict)

print(item_list)

EDIT (some more explanation):

#lets create a list
list_ = [x ** 2 for x in range(0,10)]
print(list_)

this returns:

[0,1,4,9,16,25,36,49,64,81]

You can write this as:

 list_ = []
 for x in range(0,10):
     list_.append(x ** 2)

So in that example yes you read it 'backwards'

Now assume the next:

#lets create a list
list_ = [x ** 2 for x in range(0,10) if x % 2 == 0]
print(list_)

this returns:

[0,4,16,36,64]

You can write this as:

 list_ = []
 for x in range(0,10):
     if x % 2 == 0:
         list_.append(x ** 2)

So thats not 100% backwards, but it should be logical whats happening. Hope this helps you!

NemoMeMeliorEst
  • 513
  • 4
  • 10