0

I have a CSV that looks like this except obviously bigger. What I need to do is iterate through the whole CSV and assign each individual person to their own dictionary and then create a list of those dictionaries. I've been chipping away at this and I need some guidance and help. Here is what I have so far:

with open('filename.csv', mode ='r') as file:
    reader = csv.reader(file, delimiter = ',')
        for row in itertools.islice(lvr, 0, 3):
            #here is where I am stuck

So basically this is what is hard for me to figure out:

  1. How do I take that information and put it in it's own dictionary with keys like 'name', 'address', 'city', 'date', and 'amount'?
  2. How do you step 3 lines every time?
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
KGBeans
  • 109
  • 1
  • 6

1 Answers1

2

You can use the DictReader.

import csv
with open('names.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['first_name'], row['last_name'])

Each row will be a dictionary already. You can store however you wish (append them to a list, etc.)

It will use the first row as the dictionary keys. If your csv doesn't have fieldnames in the first row. You can pass them manually to the DictReader

reader = csv.DictReader(csvfile, fieldnames=['first_name', 'last_name'])

To iterate by every 3rd line

for row in itertools.islice(reader, 0, None, 3):
    ...
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118