[Tutor] Dictionary of dictionaries of dictionaries of lists.

Morten Liebach m at mongers.org
Wed Jul 7 12:36:40 CEST 2004


I'm writing code to generate my static weblog pages, later rsync'ed to
the server (I can't and won't run serverside programs on it), from a
PostgreSQl database.
Each entry have a 'id' and 'date' field, and I want a datastructure of a
dictionary (named "entries") with years as keys, values of a dictionary
with months as keys, holding a dictionary with days as keys, value of a
list of id's for entries that day.

I have the following code:

import psycopg

connection = psycopg.connect("dbname=blog user=m")
cursor = connection.cursor()

cursor.execute("SELECT id, date FROM blog")
idx = cursor.fetchall()
entries = {}
for i in range(len(idx)):
    entries[idx[i][1].year] = \
            {idx[i][1].month : {idx[i][1].day : [].append(idx[i][0])}}

print idx[23]
print entries[2004]

The output:
(30, <DateTime object for '2003-03-02 19:44:58.00' at 3c118a68>)
{4: {20: None}}

The first line is OK, but in the second one I  expected something more
{1: {1: [67], 3: [68], 4: [69, 70]}, 2: {17: [71]}}

(Not exactly the entries in my database, there's a lot more, but you get
the picture I hope)

I'm clearly doing something wrong.  Something's missing, but what, and
(more important) why?  I might have stared myself blind on this problem
by now, so I need a push. :-)  Maybe even a rethink of it all.

I'm a python beginner, but not new to programming.  I've been doing
mostly perl and some C# the last year.

I use OpenBSD 3.5-current, Python 2.3.3, psycopg 1.1.11, mxDateTime
2.0.5 and PostgreSQL 7.4.2.

Have a nice day

http://m.mongers.org/ -- http://gallery.zentience.org/

More information about the Tutor mailing list