[Tutor] Bigrams and nested dictionaries

Michael Broe mbroe at columbus.rr.com
Wed Mar 29 07:15:30 CEST 2006

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['a'] = {'a':1, 'b':2}    #oops
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
NameError: name 'D' is not defined
 >>> D = {}
 >>> D['a'] = {'a':1, 'b':2}
 >>> D
{'a': {'a': 1, 'b': 2}}
 >>> 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}}

And Kent wrote:

"Encapsulating this in a generator is probably a good plan."

Yay, I get to play with generators... thanks for the suggestion, I  
would never have looked in that direction.

Python: [x for S in L for x in S]
Mathematica: Flatten[L] (but where's the fun in that?)

More information about the Tutor mailing list