Can dictionaries be nested?

techiepundit at futurepundit.com techiepundit at futurepundit.com
Wed Jan 11 21:54:40 EST 2006


I'm parsing some data of the form:

OuterName1  InnerName1=5,InnerName2=7,InnerName3=34;
OuterName2  InnerNameX=43,InnerNameY=67,InnerName3=21;
OuterName3 ....
 and so on....

These are fake names I've made up to illustrate the point more clearly.

(the embedded device device can't produce XML and this is what I have
to deal with)

I want to populate a nested set of dictionaries where the outer most
dictionary has look-ups on the OuterNames:

InnerDict = OuterDict["OuterName2"]

Then InnerDict[InnerName3] would yield 21 in the above example.

First, can dictionaries contain dictionaries?

Second, how to create each successive inner dictionary when populating
it? Python doesn't have constructors and (having all of 4 weeks of
Python experience) it isn't clear to me whether in nested while loops
that variables ever go out of scope.

If I do:

OuterDict = {}
while populating dictionaries
   InnerDict = {}
   while inner stuff to populate
      InnerDict["InnerName1"] = 5
      .. and so on
     :
   OuterDict["OuterName1"] = InnerDict

 then when I loop around the second time will the same InnerDict get
set back to an empty dictionary and therefore wipe out the dictionary I
put at OuterDict["OuterName1"] ?

I need a new inner dictionary each time thru the outer while loop. It
is not clear to me how to do this.




More information about the Python-list mailing list