user3127632
user3127632

Reputation: 373

Add Dictionary to a list python

I am new to python and I'm trying to create a csv parsing script. I pass rows from the csv to a list but what currently troubles me is that I need to add the first header line as a dictionary in each item.

def parse_csv(datafile):     
    data = []
    with open(datafile, "r") as f: 
        next(f) #skip headerline
        for line in f:
            splitLine = line.strip(',') 
            rowL = splitLine.rstrip('\n') #remove the newline char
            data.append(rowL)
        pprint(data)

    return data

If the 1st header line has the dictionaries (e.g Title, Name etc) how am I going to pass to each stripped element?

e.g {'Dict1': 'data1', 'Dict2': 'data2' }

This may be considered duplicate but tried various ways from similar posts but none worked properly on my case.

Upvotes: 0

Views: 144

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 881585

@GeorgiDimitrov is certainly right that the proper approach is to use the csv module from the standard library, but, if you're doing this only for self-instruction purposes, then...:

def parse_csv(datafile):     
    data = []
    with open(datafile, "r") as f: 
        headers = next(f).split(',')
        for line in f:
            splitLine = line.split(',') 
            dd = dict(zip(headers,splitLine))
            data.append(dd
    pprint(data)

return data

This will not properly deal with quoted/escaped commas, &c -- all subtleties that are definitely best left to the csv module:-).

Upvotes: 2

Georgi Dimitrov
Georgi Dimitrov

Reputation: 173

I strongly recommend to use the provided csv library. It will save you a lot of time and effort. Here is what you want to do:

import csv
data = []
with open(datafile, 'r') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        data.append(row)
        print(row['Title'], row['Name'])

In this example each row is actually a python dictionary.

Upvotes: 6

Related Questions