[Tutor] Bigrams and nested dictionaries
Kent Johnson
kent37 at tds.net
Tue Apr 4 11:57:54 CEST 2006
Michael Broe wrote:
> dict = {}
dict is the name of the builtin dictionary class, so you shouldn't use
it as the name of your dict - you shadow the built-in name. file is also
a built-in name.
>
> L = file[0]
> for R in file[1:]: # move right edge of window across the file
> if not L in dict:
> dict[L] = {}
>
> if not R in dict[L]:
> dict[L][R] = 1
> else:
> dict[L][R] += 1
I might write it this way:
dictL = dict.setdefault(L, {})
dictL[R] = dictL.setdefault(R, 0) + 1
though I'm not sure which way will be faster.
Kent
More information about the Tutor
mailing list