简体   繁体   中英

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

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.

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.

Other way is to create a tuple and convert to dictionary the tuples, will work for even for txt files.

for row in reader:
    ID = row[0] 
    data_type = row[1]
    myTuples.append(tuple([ID, data_type]))

result = dict(myTuples)
print result

resuling:

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

you can skip header or first row on read the data/csv so 'ID': ' type' will not be in dict.

shortest way skip first row and also append positions of the row without creating ID and type variables:

next(f) #for skipping first row in the file
myTuples = [] #store tuples from col1 and col2
for row in reader:
    myTuples.append(tuple([row[0], row[1]])) #append col1 and col 2 to myTuples

result = dict(myTuples)
print result

resulting:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM