How complex is complex?

Paul McGuire ptmcg at austin.rr.com
Wed Mar 18 14:10:37 EDT 2009


You realize of course that these two alternatives are not equivalent.
The first does what your problem statement describes, for each key in
a given dict, increments the corresponding value.  The second creates
an entirely new dict with the modified values.  Even if you were to
write the second one as

a = dict(map(lambda key: (key, a[key] + 1), a))

This would not necessarily accomplish the same effect as the for loop.
If a is an argument to a function, then the for-loop actually updates
the given dict in place, so that the effects of the increment-by-one
for loop will be seen in the caller after this function ends.
However, constructing a new dict and assigning to 'a' only affects the
value of a in the local function - the caller's dict will be
unaffected.

For updating in place, as in your first example, I am hard-pressed to
come up with a simpler form (ah, thank you bearophile for looping over
iteritems instead of the keys).  But if constructing a new dict is an
acceptable approach, then the dict/map/lambda approach you have posted
is functional overkill.  To do the iteration over 'a' that map does
with the lambda, you may as well do with a list comprehension, in far
more readable form:

a = dict((k,v+1) for k,v in a.iteritems())

If you are using Py2.6 or 3.0, you can use the new dict comprehension
form:

a = {k:v+1 for k,v in a.iteritems()}

Would you *really* want to take the position that the map/lambda form
is easier to follow than this?

-- Paul




More information about the Python-list mailing list