dict literals vs dict(**kwds)

George Sakkis george.sakkis at gmail.com
Fri May 26 16:55:13 CEST 2006


Duncan Booth wrote:

> George Sakkis wrote:
>
> > 2) restricting in a more serious sense: the future addition of optional
> > keyword arguments that affect the dict's behaviour. Google for "default
> > dict" or "dictionary accumulator".
>
> There is nothing to stop dictionaries being created using factory functions
> (e.g. see dict.fromkeys). So one possible way to implement defaults would
> be to extend the dict class with a new classmethod 'withdefault' which
> takes a default value as an argument.
>
> However, given that the default argument isn't actually needed during
> construction, it doesn't seem to me that it fits either as a constructor
> parameter nor a factory method. I don't see why it shouldn't just be set on
> an existing dictionary (or dictionary subclass) when you need it.

Because I would find

d = dict(default=0)
d['x'] += 3

more elegant than

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

YMMV,
George




More information about the Python-list mailing list