开发者

csv to OrderedDict

开发者 https://www.devze.com 2023-03-08 10:45 出处:网络
How can I make OrderedDict from csv? Is there any function? csv: 1 one 2 two O开发者_运维百科rderedDict:

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

csv:

1 one
2 two

O开发者_运维百科rderedDict:

OrderedDict((('1', 'one'), ('2', 'two')))


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)


In Python 3, the CSV module can import a CSV file and convert rows directly to instances of OrderedDict, with the order of the keys consistent with your CSV file. This is a departure from Python 2 behavior where the rows were returned as plain dict types.

import csv
from pprint import pprint

with open(filename) as fd:
    for row in csv.DictReader(fd):
        pprint(row)
Date,Name,Notes
31 May 2019,Robert,
1 June 2019,Silvio,
OrderedDict([('Date', '31 May 2019'),
             ('Name', 'Robert'),
             ('Notes', '')])
OrderedDict([('Date', '1 June 2019'),
             ('Name', 'Silvio'),
             ('Notes', '')])
...


I had the same issue, easy way was to subclass and tweak a csv function. Here is my working bit of code: http://code.activestate.com/recipes/577996-ordered-csv-read-write-with-colum-based-lookup/?in=user-4177968


There's a csv module that includes a reader. In general, you can turn a list of tuples into a dictionary like so:

d = OrderedDict((k, v) for k, v in listOfTuples)


Although the solution is accepted, my alternative solution would suit the situation where the key can be located in any columns::

>>> import pyexcel as pe
>>> csv = pe.Sheet("your.csv", name_rows_by_column=0)
>>> your_dict = csv.to_dict() # Voila, OrderredDict in return!

where name_rows_by_column can be any index of the available columns.

0

精彩评论

暂无评论...
验证码 换一张
取 消