dict literals vs dict(**kwds)

Duncan Booth duncan.booth at invalid.invalid
Fri May 26 14:25:54 EDT 2006


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.




More information about the Python-list mailing list