[Tutor] creating a nested dictionary
Garry Willgoose
garry.willgoose at newcastle.edu.au
Thu Jan 24 08:20:19 CET 2008
Is there any easy way to create a nested dictionary. I want to be
able to allocate like
pdb[dataset][modulename][parametername]['value']=value
where dataset, modulename, parametername are variables that are
determined within loops nested 3 deep, and value comes from a
database call. Prior to the nested loops I do not know what the
values of dataset, modulename, parametername will range over, but I
do know pdb needs to be nested 3 deep. What I'd like to do is
something like this
pdb={}
for dataset in dataset_list:
modulename_list=getmodules(dataset)
for modulename in modulename_list:
parametername_list=getparameters(dataset,modulename)
for parametername in parametername_list:
value=getvalue(dataset, modulename, parametername)
pdb[dataset][modulename][parametername]['value']=value
What I'm currently doing is
pdb={}
for dataset in dataset_list:
modulename_list=getmodules(dataset)
moduledict={}
for modulename in modulename_list:
parametername_list=getparameters(dataset,modulename)
valuedict={}
for parametername in parametername_list:
value=getvalue(dataset, modulename, parametername)
valuedict['value']=value
# valuedict needs to be a dictionary because there is other stuff
valuedict['otherstuff]=otherstuff
...
parameterdict[parametername]=valuedict.copy()
moduledict[modeulename]=copy.deepcopy(parameterdict)
pdb[dataset]=copy.deepcopy(moduledict)
Now I know the 2nd is not that much more complex but this is a pretty
common construct in what I'm doing so I'm just wondering if there is
a clear and simple shortcut ;-)
====================================================================
Prof Garry Willgoose,
Australian Professorial Fellow in Environmental Engineering,
Director, Centre for Climate Impact Management (C2IM),
School of Engineering, The University of Newcastle,
Callaghan, 2308
Australia.
Centre webpage: www.c2im.org.au
Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574
(Fri PM-Mon)
FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal
and Telluric)
Env. Engg. Secretary: (International) +61 2 4921 6042
email: garry.willgoose at newcastle.edu.au;
g.willgoose at telluricresearch.com
email-for-life: garry.willgoose at alum.mit.edu
personal webpage: www.telluricresearch.com/garry
====================================================================
"Do not go where the path may lead, go instead where there is no path
and leave a trail"
Ralph Waldo Emerson
====================================================================
More information about the Tutor
mailing list