[Tutor] request for comments regarding my function

Isaac hyperneato at gmail.com
Sun Oct 25 07:49:17 CET 2009

Hello all,
I wrote a function to organize a list of sorted objects ( django blog
entries ); each object has a Python datetime attribute ( called
pub_date ). I am posting a message to the tutor mailing list to get
feedback regarding better ways to accomplish the same task. I have a
feeling I could use recursion here, instead of looping through the
entire _query list 3 times. Here is my code:

def create_archive_list(_query):
    given a sorted queryset, return a list in the format:

    archive_list = [{'2009': [{'December': ['entry1', 'entry2']},
                              {'January': ['entry3', 'entry4']}

                    {'2008': [{'January': ['entry5', 'entry6']},

    archive_list = []
    tmp_year_list = []

    # make a list of Python dictionaries; the keys are the year, as in
'2009', and the value
    # is an empty list.
    for item in _query:
        if item.pub_date.year not in tmp_year_list:
            tmp_dict = {}
            tmp_dict[item.pub_date.year] = []

    # for every list in the archive_list dictionaries, append a
dictionary with the
    # blog entry's month name as a key, and the value being an empty list
    for entry in _query:
        for item in archive_list:
            _year = entry.pub_date.year
            if _year in item:
                _tmp_month = entry.pub_date.strftime("%B")
                # make a dictionary with the month name as a key and
an empty list as a value
                tmp_dict = {}
                tmp_dict[_tmp_month] = []

                if tmp_dict not in item[_year]:

    # append the blog entry object to the list if the pub_date month
and year match
    # the dictionary keys in the archive_list dictionary/list tree.
    for entry in _query:
        # dict in list
        for item in archive_list:
            # year of entry
            _year = entry.pub_date.year
            if _year in item:
                _year_list = item[_year]
                for _dict_month in _year_list:
                    _tmp_month = entry.pub_date.strftime("%B")
                    if _tmp_month in _dict_month:

    return archive_list

More information about the Tutor mailing list