Skip to content

Instantly share code, notes, and snippets.

@samuell
Created February 1, 2013 18:41
Show Gist options
  • Save samuell/4693184 to your computer and use it in GitHub Desktop.
Save samuell/4693184 to your computer and use it in GitHub Desktop.
Read a tab separated file, with headers, into a "list" (or a generator object returning items, but behaves similar), where each dict uses the headers in the first line as keys.
'''
Read a tab separated file, with headers, into a "list" (or better,
a generator object returning items, but behaves similar), where
each dict uses the headers in the first line as keys.
Author: Samuel Lampa 2013 - [email protected]
'''
# Open file
infile = open(some_filename)
# Parse first line into column names
col_names = infile.next().split("\t")
# Create a dict from every row in the file (except the header line),
# with the column names created above
rows_as_dicts = (dict(zip(col_names, row.split("\t"))) for row in infile)
# Look at first line
print rows_as_dicts.next()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment