Enter dates from Python groupby

I have a collection of news article objects that I want to display archived in a single month. I used itertools.groupbyto create a list of Python objects arranged in this way:

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)))
]

So I have a collection like:

[{'date': datetime.datetime(2011, 1, 1, 0, 0), 
  'list': [<News: A January Article>, <News: Another January Article>]}, 
 {'date': datetime.datetime(2010, 12, 1, 0, 0), 
  'list': [<News: Happy Xmas>]}, 
 {'date': datetime.datetime(2010, 10, 1, 0, 0), 
  'list': [<News: Halloween>]}, 
 {'date': datetime.datetime(2010, 1, 1, 0, 0), 
  'list': [<News: Old old old Jan 2010>]}]

I would like to populate the news_grouped collection so that it includes an entry for each month between the oldest article and today's date, and empty ones with an empty list.

I understand that I can do this by moving from the oldest date to the newest date and filling out the collection, but something about it just doesn’t quite sit with me, and I think that is also not very effective.

Is there a more elegant way to solve this? Can someone point me to one?

( Django , , python - , , )

.

.

+3
1

Space_C0wb0y, , dict, 2.7.

  • oldest.pub_date
  • dict
0

Source: https://habr.com/ru/post/1795475/


All Articles