0

Imagine a CSV that looks like

Zipcode  State
0000     CA
0001     CA

I want to create a dictionary where the Key is the zipcode and the Value is the State.

I've already written a function that reads the CSV line by line,

for i, line in enumerate(reader):
    print ('line[{}] = {}'.format(i, line))

output: 
line[1] = ['0000', 'CA']
line[2] = ['0001', 'CA']

How do I take each line and make it an entry in dictionary? Hoping for an output as return dict[zipcode]

nafcb10
  • 33
  • 1
  • 5
  • Welcome to SO. Please take the time to read [ask] and the other links found on that page. This isn't a discussion forum or Tutorial. – wwii Jun 26 '19 at 21:16

2 Answers2

0

Since you've already made an iterator over parsed lines you can just use a dictionary comprehension to get what you want.

{line[0]: line[1] for line in reader}
Kyle Parsons
  • 1,475
  • 6
  • 14
  • is this all I have to write? how do i use the dictionary comprehension? it doesn't seem to be working – nafcb10 Jun 26 '19 at 21:13
  • How is it not working for you? I'm unable to reproduce any problems you are having because I don't know how your `reader` variable is defined. – Kyle Parsons Jun 26 '19 at 21:17
  • My code is `import csv with open('ZIPCODE.csv', 'r') as csv_file: reader = csv.reader(csv_file, delimiter="\t") for i, line in enumerate(reader): print ('line[{}] = {}'.format(i, line)) mydict = {line[0]: line[1] for line in reader}` Error I get: `Traceback (most recent call last): File "", line 11, in File "", line 11, in ValueError: I/O operation on closed file.` Line 11 = `{line[0]: line[1] for line in reader}` – nafcb10 Jun 26 '19 at 21:31
  • It looks like that when you `enumerate(reader)` you're consuming the iterator returned by `csv.reader`. So when you go to use that iterator for the dictionary comprehension there are no lines left to comprehend over. Also if you try to access the reader outside of the `open` context you'll get that I/O error. – Kyle Parsons Jun 26 '19 at 21:38
0

Alternative approach using pandas.read_csv

import pandas as pd

df=pd.read_csv(file_path)
df.set_index('Zipcode').T.to_dict(orient='records')[0]

OUTPUT:

{'0000': 'CA', '0001': 'CA'}
Ricky Kim
  • 1,992
  • 1
  • 9
  • 18