[Python-Dev] dict.addlist()

Phillip J. Eby pje at telecommunity.com
Tue Jan 20 09:56:57 EST 2004


At 09:26 AM 1/20/04 -0500, Bob Ippolito wrote:
>There are other reasons to use setdefault.  This one is pretty common 
>though, but I think a more generic solution could be implemented.
>
>Perhaps:
>
>d.setdefault(k, factory=list).append(v) ?

+100.  :)  An excellent replacement for my recurring use of:

try:
     return self._somemapping[key]
except:
     self._somemapping[key] = value = somethingExpensive(key)
     return value


That becomes simply:

     return self._somemapping.setdefault(
         key, factory=lambda: somethingExpensive(key)
     )




More information about the Python-Dev mailing list