Created
April 10, 2015 14:08
-
-
Save Averroes/5301c9583a89c5167943 to your computer and use it in GitHub Desktop.
grouping-records-together-based-on-a-field
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
rows = [ | |
{'address': '5412 N CLARK', 'date': '07/01/2012'}, | |
{'address': '5148 N CLARK', 'date': '07/04/2012'}, | |
{'address': '5800 E 58TH', 'date': '07/02/2012'}, | |
{'address': '2122 N CLARK', 'date': '07/03/2012'}, | |
{'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'}, | |
{'address': '1060 W ADDISON', 'date': '07/02/2012'}, | |
{'address': '4801 N BROADWAY', 'date': '07/01/2012'}, | |
{'address': '1039 W GRANVILLE', 'date': '07/04/2012'}, | |
] | |
from itertools import groupby | |
rows.sort(key=lambda r: r['date']) | |
for date, items in groupby(rows, key=lambda r: r['date']): | |
print(date) | |
for i in items: | |
print(' ', i) | |
# Example of building a multidict | |
from collections import defaultdict | |
rows_by_date = defaultdict(list) | |
for row in rows: | |
rows_by_date[row['date']].append(row) | |
for r in rows_by_date['07/01/2012']: | |
print(r) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment