[Feature Request] dict.setdefault()

Tim Chase python.list at tim.thechases.com
Mon Apr 11 19:25:54 EDT 2011

On 04/11/2011 05:44 PM, Chris Angelico wrote:
> On Tue, Apr 12, 2011 at 8:41 AM, MRAB<python at mrabarnett.plus.com>  wrote:
>> I'm not sure that "setdefault" should take **kw args for this because
>> of its existing argument structure (key + optional value).
>> A new method like "updatedefault" may be better, IMHO. It would act
>> like "update" except that it wouldn't overwrite existing values.
> Wouldn't x.updatedefault(y) be pretty much y.update(x) ?

As I understand, the difference would be the following pseudocode:

  def update(self, d):
    for k,v in dict(d).iteritems():
      self[k] = v

  def updatedefault(self, d={}, **kwargs):
    for k,v in chain(
      # MRAB's comment about "wouldn't overwrite existing"
      if k not in self:
        self[k] = v

My concern with the initial request is that dict.setdefault() 
already returns the (existent or defaulted) value, so you can do 
things like

   d.setdefault(my_key, []).append(item)

If you allow it to take multiple kwargs, what would the return 
value be (positionality of kwargs is lost, so returning a tuple 
wouldn't be readily possible)?

Finally, if it were added, I'd call it something like merge()


More information about the Python-list mailing list