map-like function on dict values?
Skip Montanaro
skip at pobox.com
Wed Feb 27 20:57:21 EST 2002
Huaiyu> Is there a way to do this
Huaiyu> for k, v in dict.items():
Huaiyu> dict[k] = f(v)
Huaiyu> without involving a Python for loop?
Check out the operator module. In particular, operator.setitem will
probably do what you want:
import operator
keys = dict.keys()
vals = map(f, dict.values())
map(operator.setitem, [dict]*len(keys), keys, vals)
Huaiyu> I'd imagine that a function implemented in C could speed things
Huaiyu> up quite a bit.
It all depends on how expensive f() is related to the overhead of a for loop
and the cost of getting map ramped up. Don't rely on your instincts.
Benchmark it.
--
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)
More information about the Python-list
mailing list