dict literals vs dict(**kwds)

Paul Rubin http
Fri May 26 14:50:42 EDT 2006


Duncan Booth <duncan.booth at invalid.invalid> writes:
> > d = dict(default=0)
> > d['x'] += 3
> > 
> > more elegant than
> > 
> > d = {}
> > d.withdefault(0)
> > d['x'] += 3
> > 
> Well you could have:
> 
>  d = dict.withdefault(0)
> 
> but then you may have to start with an empty dictionary. What happens if 
> you need to change default for different uses?

It might be nice to have something like:

   d = {}
   ...
   d.withdefault(0)['x'] += 3

d.withdefault would have to construct some special object whose
__iadd__ did the right thing to make this happen.

This would also let you do stuff like:

   d = {}
   d0 = d.withdefault(0)    # can similarly make d1, d2, etc.
   ...
   d0['x'] += 3



More information about the Python-list mailing list