[Tutor] Bigrams and nested dictionaries
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Mon Apr 3 20:39:56 CEST 2006
> 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!
More information about the Tutor
mailing list