reduce() anomaly?
David C. Fox
davidcfox at post.harvard.edu
Wed Nov 5 13:28:24 EST 2003
Stephen C. Waterbury wrote:
> This seems like it ought to work, according to the
> description of reduce(), but it doesn't. Is this
> a bug, or am I missing something?
>
> Python 2.3.2 (#1, Oct 20 2003, 01:04:35)
> [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> d1 = {'a':1}
> >>> d2 = {'b':2}
> >>> d3 = {'c':3}
> >>> l = [d1, d2, d3]
> >>> d4 = reduce(lambda x, y: x.update(y), l)
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "<stdin>", line 1, in <lambda>
> AttributeError: 'NoneType' object has no attribute 'update'
> >>> d4 = reduce(lambda x, y: x.update(y), l, {})
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "<stdin>", line 1, in <lambda>
> AttributeError: 'NoneType' object has no attribute 'update'
>
> - Steve.
The update method updates the dictionary in place, but returns None.
Thus, after the first call to x.update(y), reduce is trying to call
x.update(y) with x equal to None. Hence the error.
Alternatives which work include
def rupdate(d, other):
d.update(other)
return d
reduce(rupdate, l)
and
d = {}
map(lambda x: d.update(x), l)
David
More information about the Python-list
mailing list