Skip to content

Instantly share code, notes, and snippets.

@eightysteele
Created October 4, 2011 00:33
Show Gist options
  • Select an option

  • Save eightysteele/1260628 to your computer and use it in GitHub Desktop.

Select an option

Save eightysteele/1260628 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import csv
import tempfile
def generator(reader):
"""Generates dictionaries from a DictReader that contain only 'a' and 'b' keys."""
cols = ['a', 'b']
for row in reader:
yield dict((key,val) for key,val in row.iteritems() if key in cols)
if __name__ == '__main__':
data = ('a,b,c', '1,2,3', '4,5,6')
dr = csv.DictReader(data)
# Prints:
# {'a': '1', 'b': '2'}
# {'a': '4', 'b': '5'}
for line in generator(dr):
print line
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment