dict literals vs dict(**kwds)

George Sakkis george.sakkis at gmail.com
Fri May 26 14:56:17 EDT 2006


Duncan Booth wrote:

> George Sakkis wrote:
>
> > 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
> >
> 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?
>
> Wouldn't wrapping the dictionary in an adaptor be a simpler solution? In
> many cases the place where you are going to know what default is
> appropriate will be separated from the place where you create the
> dictionary. You should be able to write a function which takes a dictionary
> as parameter and accumulates values into it.

I bet that usually when you create a dictionary, you either populate it
right away or at least you know what kind of items are going to be
added, e.g. "word -> count" or "word -> list of indexes it appears". In
such cases you typically know the default value as well, e.g. 0 or [].
Do you have many use cases where you make a dict without knowing what
is it going to store or where the default might change during the
dict's lifetime ? I can't think of any.

George




More information about the Python-list mailing list