Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 264
ahtmatrix Avatar asked Oct 24 '16 21:10

ahtmatrix


2 Answers

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.

like image 60
Erik Godard Avatar answered Nov 15 '22 00:11

Erik Godard


It's simpler than you thought:

import csv

with open('TIS_annotation.csv') as f:
    next(f)  # Skip the header
    reader = csv.reader(f, skipinitialspace=True)
    result = dict(reader)
    print result

Output:

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

Basically, reader yields a series of rows, each has two elements, feed that into dict and you have it made.

like image 34
Hai Vu Avatar answered Nov 15 '22 00:11

Hai Vu