Skip to content

Instantly share code, notes, and snippets.

@drillbits
Created July 26, 2012 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drillbits/3180273 to your computer and use it in GitHub Desktop.
Save drillbits/3180273 to your computer and use it in GitHub Desktop.
namedtupleでcsvの各行をリストではなく定義した列名をキーとした辞書として扱う
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