On Wed, 2006-03-29 at 00:15 -0500, Michael Broe wrote:
> Aha! John wrote:
> 
> "Are you sure you haven't mistakenly assigned something other than a  
> dict to D or D['d'] ?"
> 
> Thanks for the tip! Yup that was it (and apologies for not reporting  
> the problem more precisely). I hadn't initialized the nested  
> dictionary before trying to assign to it. (I think Perl doesn't  
> require initialization of dictionaries prior to assignment, which in  
> this case, would be a nice thing...)
> 

>  >>> D['c']['a'] = 1   #ooops
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> KeyError: 'c'
>  >>> D['c'] = {}
>  >>> D['c']['a'] = 1
>  >>> D
> {'a': {'a': 1, 'b': 2}, 'c': {'a': 1}}
> 

You can check if the dictionary key exists prior to assigning to it:

>>> if not D.has_key('c'):
...    D['c'] = {}
>>> D['c']['a'] = 1


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

Reply via email to