Mac McMahan
Mac McMahan

Reputation: 27

Trying to populate a nested dictionary with .csv files within a loop in Python

I have a set of .csv spreadsheets that I would like to store in a dictionary. I want the name of the spreadsheet to be the dictionary key, and the dictionary value to be the spreadsheet saved as a dictionary. In the sub-dictionary, I want the column headers to be the keys and the column values to be the dictionary values, saved as floats. My code does something, but I cannot quite figure out what exactly it is doing.

import os
import csv

os.chdir("pathGoesHere")
path=os.getcwd()

rivers=[]
riverDat={}
for sheet in os.listdir(path):
    if sheet.endswith(".csv"):
        temp={}
        name=sheet[0:-4]
        rivers.append(name)
        reader=csv.QUOTE_NONNUMERIC(open(sheet))     
        for i in reader:
            key=i[0]
            temp[key]=i[1]
        print(temp)

an excerpt from the top of the csv

Upvotes: 1

Views: 67

Answers (1)

KVEER
KVEER

Reputation: 123

If you can use the pandas module, this code should serve the purpose. Note that riversDict is the output dictionary.

import pandas as pd

riversDict={}

for sheet in os.listdir(path):
    if sheet.endswith(".csv"):
        name=sheet[0:-4]
        dataIn=pd.read_csv(sheet)
        dataIn=dict(dataIn.apply(pd.to_numeric, errors='coerce'))
        riversDict[name]=dataIn
        print(riversDict)

Upvotes: 1

Related Questions