[Tutor] Making a dictionary of dictionaries from csv file

Rich Lovely roadierich at googlemail.com
Wed Dec 3 14:57:42 CET 2008

How about this:

def recursiveDictFactory():
    return defaultdict(recursiveDictFactory)

dictOfDictsOfDictsEtc = defaultdict(recursiveDictFactory)

Richard "Roadie Rich" Lovely
Part of the JNP|UK Famille

(Sent from my iPod - please allow me a few typos: it's a very small  

On 3 Dec 2008, at 11:43, "Kent Johnson" <kent37 at tds.net> wrote:

> On Wed, Dec 3, 2008 at 3:34 AM, Alan Gauld  
> <alan.gauld at btinternet.com> wrote:
>> Also you are overwriting the row for each name. So you only
>> store the last entry. So you need to separate the data further.
>> Something like
>> maindict[row[name]] [row[day]] = (row.weight, row,temp)
> This will not quite work. It will give KeyErrors because the
> second-level dicts don't exist in maindict. One way to fix this is to
> use collections.defaultdict:
> from collections import defaultdict
> maindict = defaultdict(dict)
> Now maindict uses an empty dictionary as its default value.
> For another level of nesting (the 'Day' level you show in your
> example) this becomes a bit more complex, see this discussion and the
> link:
> http://thread.gmane.org/gmane.comp.python.tutor/46006
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list