Created
October 4, 2011 00:33
-
-
Save eightysteele/1260628 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #!/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