[Tutor] Making a dictionary of dictionaries from csv file

Kent Johnson kent37 at tds.net
Wed Dec 3 12:43:01 CET 2008


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


More information about the Tutor mailing list