JPunelli
JPunelli

Reputation: 11

Creating a dictionary out of a CSV file in python

I have a CSV file with zip codes and their timezones. How do I convert the CSV file to a dictionary? This will be a module for a bigger assignment. My code looks like this and I'm stuck on what to do next:

import csv

with open('zipcode.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row

input_file = csv.DictReader(open("zipcode.csv"))

Upvotes: 1

Views: 185

Answers (3)

erip
erip

Reputation: 16935

This simple script should help you figure it out. You won't need to use DictReader.

test.py

import csv

# Open the file
with open('zipdata.csv') as f:
  # Populate a dictionary with the reader
  my_dict = dict(csv.reader(f))

# Print the key-value pairs
for k, v in my_dict.iteritems():
  print("{}: {}".format(k, v))

I used my own test csv file, test.csv and here's the output:

23:59 $ cat test.csv
hello, world
test, testing
✔ ~ 
23:59 $ python test.py 
test:  testing
hello:  world

Upvotes: 1

Steve Misuta
Steve Misuta

Reputation: 1033

I'm not sure what your data file looks like, but here is a way to do it using pandas DataFrame, assuming your csv file has two columns: zip_code and time_zone, separated by comma, without any headers:

import pandas as pd
df = pd.read_csv('zipdata.csv', header=None) 
my_dict = dict(zip(df[0], df[1]))

Upvotes: 1

jprockbelly
jprockbelly

Reputation: 1607

Making a guess at your file structure, try this:

import csv

my_dict = {}

with open('zipcode.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        my_dict[row[0]] = row[1]

Upvotes: 1

Related Questions