ahtmatrix ahtmatrix - 1 year ago 95
Python Question

How do I read a 2 column csv file and create a dictionary?

For example given the following csv

ID, type
1 , A
2 , B
3 , C

it should generate a dictionary that looks like this

{'1':A, '2':B, '3':C}

Here's what I have so far, but its's associating the entire column into 1 dictionary

import csv

reader = csv.DictReader(open('TIS_annotation.csv'))
result = {}

for row in reader:
for column, value in row.iteritems():
result.setdefault(column, []).append(value)
print result

Answer Source

When you iterate over each row in reader, the row variable contains all the information you need to make a new entry to the dictionary. You can simply write

for row in reader:
    result[row['ID']] = row[' type']

To make the dictionary you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download