Note that there are some explanatory texts on larger screens.

plurals
  1. POFill dates from Python groupby
    text
    copied!<p>I have a collection of news article objects which I wish to display archived by distinct month. I've used <code>itertools.groupby</code> to create a list of Python objects ordered in such a way:</p> <pre><code>news_grouped = [ {'date': key, 'list': list(val)} for key, val in groupby(obj_list, (lambda v: datetime.datetime(v.pub_date.year, v.pub_date.month, 1))) ] </code></pre> <p>So I end up with a collection like:</p> <pre><code>[{'date': datetime.datetime(2011, 1, 1, 0, 0), 'list': [&lt;News: A January Article&gt;, &lt;News: Another January Article&gt;]}, {'date': datetime.datetime(2010, 12, 1, 0, 0), 'list': [&lt;News: Happy Xmas&gt;]}, {'date': datetime.datetime(2010, 10, 1, 0, 0), 'list': [&lt;News: Halloween&gt;]}, {'date': datetime.datetime(2010, 1, 1, 0, 0), 'list': [&lt;News: Old old old Jan 2010&gt;]}] </code></pre> <p>I would like to fill the news_grouped collection so that it includes an entry for each month between the oldest article and today's date, with empty ones just having an empty list.</p> <p>I realize I can do this by iterating from the oldest date to the newest date, and filling the collection, but something about that just doesn't quite sit right with me, and I'd imagine it's not very efficient either.</p> <p>Is there a more elegant way of solving this? Can anyone point me at one?</p> <p>(I'm actually using Django and was using regroup, but it seems like I'm better solving this in python outside of the templates - I could of course be wrong)</p> <p>Many thanks.</p> <p>Ludo.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload