Skip to content

Instantly share code, notes, and snippets.

@neurosnap
Last active August 29, 2015 14:03
Show Gist options
  • Save neurosnap/c1580fe7b33f65330c23 to your computer and use it in GitHub Desktop.
Save neurosnap/c1580fe7b33f65330c23 to your computer and use it in GitHub Desktop.
Array of dictionaries to group data
@app.route('/')
def landing():
arts = Articles.query.\
filter(Articles.active==True).\
filter(Articles.ready==True).all() #.\
#order_by(desc(Articles.created)).all()
# get today's date
today = datetime.date.today()
articles_grouped = []
for article in arts:
date = article.created.date()
found_date = False
new_group = { "date": date, "articles": [article] }
if len(articles_grouped) > 0:
for group in articles_grouped:
if group["date"] == date:
group["articles"].append(article)
found_date = True
break
if not found_date:
articles_grouped.append(new_group)
else:
articles_grouped.append(new_group)
# sort list by date in descending order
articles_grouped.sort(key=lambda d: d["date"], reverse=True)
return render_template('landing.html', articles=articles_grouped)
# -------------
@app.route('/')
def landing():
arts = Articles.query.\
filter(Articles.active==True).\
filter(Articles.ready==True).all() #.\
#order_by(desc(Articles.created)).all()
# get today's date
today = datetime.date.today()
articles_grouped = {}
for article in arts:
curr_date = article.created.date()
if curr_date in articles_grouped:
articles_grouped[curr_date].append(article)
else:
articles_grouped[curr_date] = [article]
articles = OrderedDict(sorted(articles_grouped.iteritems(), reverse=True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment