ryan doucette
ryan doucette

Reputation: 83

Creating an OrderedDict from a csv file

What I am trying to do is take a csv file with several rows and columns of data and make an ordered dictionary that I can call on and iterate through later.

This is what it looks like when I open and print the csv file in my python shell:

"csv printed"

​And here is the code I have now and am playing with in the shell:

from collections import OrderedDict

aDict = OrderedDict()
order = next(csv.reader(file))[1:]
file.seek(0)
csvReader = csv.DictReader(file)
for row in csvReader:
    key = row.pop("key")
    aDict[key] = OrderedDict((k, row[k]) for k in order)

"my unworking code"

I want it to iterate over each line and write the dictionary with the keys being the dates and the values as a list of the other values in each column.

Ex: {"12/12/1980" : [28.75,28.87,28.75,28.75,2093900.0,0.0,1.0]}

Upvotes: 1

Views: 2442

Answers (1)

eestrada
eestrada

Reputation: 1603

I don't know why you are trying to pop keys off of the dictionary and items off the list. It doesn't seem to serve your purpose of creating an OrderedDict.

This is the solution I came to. It doesn't pop any items (again because I don't know exactly why you are doing that).

import csv
from collections import OrderedDict

file = open('example.csv', mode='r')

csvReader = csv.reader(file)

# get rid of header row
header = next(csvReader)
# print(header)

odict = OrderedDict()
for row in csvReader:
    odict[row[0]] = row[1:]
    # print(row)

print(odict)

This could be cleaner and more reusable if it is put into a function, like so:

import csv
from collections import OrderedDict

def parse_csv(filename):

    file = open(filename, mode='r')

    csvReader = csv.reader(file)

    # get rid of header row
    header = next(csvReader)
    # print(header)

    odict = OrderedDict()
    for row in csvReader:
        odict[row[0]] = row[1:]
        # print(row)

    return odict

parse_csv('example.csv')

Upvotes: 3

Related Questions