[Tutor] Dictionary of dictionaries of dictionaries of lists.

Alan Gauld alan.gauld at blueyonder.co.uk
Wed Jul 7 21:48:53 CEST 2004


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

Might make it slightly clearer if you use

for id in idx:
      entries[id[1].year] = ....

using a for loop with a range(len combo is usually wrong,
either you would be better with a while or to iterate over
the collection itself.

>     entries[idx[i][1].year] = \
>             {idx[i][1].month : {idx[i][1].day :
[].append(idx[i][0])}}

I'm not sure I understand this bit. You are creating a new
dictionary with a single key which has another new dictionary also
with
a single key with a list with a single value?

Would a simple tuple not be a better solution?

Or are you (as I suspect you are) trying to add new entries to the
existing ones? So that you can evaluate entries[2004][03][21]
and get back a list?

> 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.

The problem is you are creating a brand new dictionary each time and
nuking the previous entry...

You need to add to the existing dictionary not replace it. Because
you have such a deeply nested structure you will probably need to do
this in multiple steps I suspect.

HTH,

Alan G.



More information about the Tutor mailing list