Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

csv to OrderedDict

Tags:

python

How can I make OrderedDict from csv? Is there any function?

csv:

1 one
2 two

OrderedDict:

OrderedDict((('1', 'one'), ('2', 'two')))
like image 963
Qiao Avatar asked Dec 16 '22 13:12

Qiao


1 Answers

If your csv has two columns as described in your question, you can do this:

import csv
import collections

with open('foo.csv','rb') as f:
    r = csv.reader(f)
    od = collections.OrderedDict(r)

If the rows in the csv file were formatted as key, value1, value2, value3 you would do this:

with open('foo.csv','rb') as f:
    r = csv.reader(f)
    od = collections.OrderedDict((row[0], row[1:]) for row in r)
like image 103
Steven Rumbalski Avatar answered Jan 01 '23 03:01

Steven Rumbalski