jhomme wrote:
Hi,
If I want to put a dictionary in a dictionary, does the syntax for assigning 
and getting at the
stuff in the inner dictionary look something like this:
outer_dictionary[inner_dictionary][key] = 'value' > ?

If inner_dictionary is the key to outer_dictionary, then that is right. For example,

Create the outer dict:
 >>> outer = {}

Create an inner dict:
 >>> outer['outerkey'] = {}

Add a key/value pair to the inner dict
 >>> outer['outerkey']['innerkey'] = 'myvalue'
 >>> outer
{'outerkey': {'innerkey': 'myvalue'}}

Retrieve the inner dict:
 >>> outer['outerkey']
{'innerkey': 'myvalue'}

Retrieve an entry from the inner dict:
 >>> outer['outerkey']['innerkey']
'myvalue'

setdefault() is handy here because you may not know if the inner dict has been created yet when you want to add an entry. If not, setdefault will do it for you:
>>> outer.setdefault('outerkey2', {})['innerkey2'] = 'anotherValue'
>>> outer
{'outerkey2': {'innerkey2': 'anotherValue'}, 'outerkey': {'innerkey': 'myvalue'}}


If the inner dict is there already setdefault will use it:
>>> outer.setdefault('outerkey2', {})['innerkey3'] = 'yetAnotherValue'
>>> outer
{'outerkey2': {'innerkey2': 'anotherValue', 'innerkey3': 'yetAnotherValue'}, 'outerkey': {'innerkey': 'myvalue'}}


Kent

Thanks.

Jim

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor

Reply via email to