[Python-Dev] Re: A small proposed change to dictionaries' "get"
method
M.-A. Lemburg
mal@lemburg.com
Thu, 03 Aug 2000 15:55:28 +0200
Guido van Rossum wrote:
>
> Marc-Andre writes:
> > The following one-liner already does what you want:
> >
> > d[word] = d.get(word, []).append('world')
>
> Are you using a patch to the list object so that append() returns the
> list itself? Or was it just late? For me, this makes d[word] = None.
Ouch... looks like I haven't had enough coffee today. I'll
fix that immediately ;-)
How about making this a method:
def inplace(dict, key, default):
value = dict.get(key, default)
dict[key] = value
return value
>>> d = {}
>>> inplace(d, 'hello', []).append('world')
>>> d
{'hello': ['world']}
>>> inplace(d, 'hello', []).append('world')
>>> d
{'hello': ['world', 'world']}
>>> inplace(d, 'hello', []).append('world')
>>> d
{'hello': ['world', 'world', 'world']}
(Hope I got it right this time ;-)
--
Marc-Andre Lemburg
______________________________________________________________________
Business: http://www.lemburg.com/
Python Pages: http://www.lemburg.com/python/