Skip to content

Instantly share code, notes, and snippets.

@flashton2003
Created September 1, 2016 15:57
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 flashton2003/8f71bfe2bbd01ade9d4cbc795234c0f5 to your computer and use it in GitHub Desktop.
Save flashton2003/8f71bfe2bbd01ade9d4cbc795234c0f5 to your computer and use it in GitHub Desktop.
from collections import Counter, defaultdict
food = [{'date':'2014', 'address':'sesame street'},{'date':'2012', 'address':'eversholt street'},{'date':'2013', 'address':'eversholt street'},{'date':'2014', 'address':'eversholt street'},{'date':'2012', 'address':'sesame street'},{'date':'2013', 'address':'sesame street'},{'date':'2014', 'address':'sesame street'},{'date':'2014', 'address':'eversholt street'},{'date':'2014', 'address':'sesame street'}]
def short_way(food):
## a default dict sets the value type to the
by_year = defaultdict(Counter)
for row in food:
# print by_year
## simultaneously adds the date as a key to the dict and incremements the counter value for the address to += 1
by_year[row['date']][row['address']] += 1
print by_year
def long_way(food):
by_year = {}
for row in food:
if row['date'] in by_year:
by_year[row['date']].append(row['address'])
else:
by_year[row['date']] = []
by_year[row['date']].append(row['address'])
year_summary = {}
for year in by_year:
year_summary[year] = Counter(by_year[year])
print year_summary
short_way(food)
# long_way(food)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment