Created
July 26, 2012 04:36
-
-
Save drillbits/3180273 to your computer and use it in GitHub Desktop.
namedtupleでcsvの各行をリストではなく定義した列名をキーとした辞書として扱う
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
import itertools | |
from collections import namedtuple | |
# 列名のリスト | |
fields = ['foo', 'bar', 'baz', 'spam'] | |
Row = namedtuple('Row', ' '.join(fields)) | |
def reader(fp): | |
reader = csv.reader(fp) | |
return itertools.imap(Row._make, reader) | |
for row in csv.reader(open('example.csv')): | |
print row | |
# -> ['FOO', 'BAR', 'BAZ', 'SPAM'] | |
for row in reader(open('example.csv')): | |
row = row._asdict() | |
print row | |
# -> OrderedDict([('foo', 'FOO'), ('bar', 'BAR'), ('baz', 'BAZ'), ('spam', 'SPAM')]) | |
print row['foo'] | |
# -> FOO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment