[Tutor] Bigrams and nested dictionaries
Victor Bouffier
victor at grupocdm.com
Tue Apr 4 00:08:00 CEST 2006
On Mon, 2006-04-03 at 11:39 -0700, Danny Yoo wrote:
> > 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
>
>
> Hi Victor,
>
> Another approach is to use the badly-named "setdefault()" method which is
> a close analogue to Perl's "autovivification" feature:
>
> ######
> >>> D = {}
> >>> D.setdefault('c', {})['a'] = 1
> >>> D
> {'c': {'a': 1}}
> ######
>
> Good luck!
>
Thanks to both Danny and Alan.
Great tips.
Victor
More information about the Tutor
mailing list