Can dictionaries be nested?

Paul Rubin http
Thu Jan 12 04:10:04 CET 2006


techiepundit at futurepundit.com writes:
> First, can dictionaries contain dictionaries?

Yes.

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

All variables stay in scope through the entire execution of the
function they're created in.

> 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"] ?

It will get set to a newly created empty dictionary.  The old
dictionary won't get wiped out, and will stay accessible through
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.

You've done it correctly.  It's pretty easy to test this stuff by
experiment.  You probably spent almost as much time posting to the
newsgroup as simply trying it would have taken:

>>> people = {}
>>> person = {}
>>> person['age'] = 25
>>> person['nationality'] = 'dutch'
>>> people['john'] = person
>>> people
{'john': {'nationality': 'dutch', 'age': 25}}
>>> person = {}  # make new dictionary
>>> people  # hasn't changed
{'john': {'nationality': 'dutch', 'age': 25}}
>>> person['age'] = 3.6e25
>>> person['nationality'] = 'cosmic'
>>> people['FSM'] = person
>>> people
{'john': {'nationality': 'dutch', 'age': 25}, 
 'FSM': {'nationality': 'cosmic', 'age': 3.6000000000000002e+25}}
>>> 



More information about the Python-list mailing list