views:

50

answers:

1

I have a function that accepts a list of date objects and should output the following dictionary in JSON:

    {
   "2010":{
      "1":{
         "id":1,
         "title":"foo",
         "postContent":"bar"
      },
      "7":{
         "id":2,
         "title":"foo again",
         "postContent":"bar baz boo"
      }
   },
   "2009":{
      "6":{
         "id":3,
         "title":"foo",
         "postContent":"bar"
      },
      "8":{
         "id":4,
         "title":"foo again",
         "postContent":"bar baz boo"
      }
   }
} 

Basically I would like to access my objects by year and month number.
What code can convert a list to this format in python that can be serialized to the dictionary above in json?

+4  A: 

Something along the lines of this should work:

from collections import defaultdict
import json

d = defaultdict(dict)
for date in dates:
    d[date.year][date.month] = info_for_date(date)
json.dumps(d)

Where info_for_date is a function that returns a dict like those in your question.

diegogs
@diegogs: Exactly what I was looking for. Thanks.But it's still not accurate enough, in one month I may have more then one object. Should this dictionary contain lists as their final values? How would that be serialized to json?
the_drow
@the_drow, you could use a `defaultdict(lambda: defaultdict(list))`. Then, do `d[date.year][date.month].append(info_for_date(date))`. That means each month will eventually hold a JSON array (of one or more JSON objects).
Matthew Flaschen
works for me, thanks :)
the_drow