Florian Brucker <[EMAIL PROTECTED]> wrote:
> That is, generate a new dict which holds for each value of the old
> dict a list of the keys of the old dict that have that very value.
> Another requirement is that it should also work on lists, in that case
> with indices instead of keys. We may assume that all values in the
> original dict/list can be used as dict keys.
import itertools
def invert(d):
def hack(d):
try:
return d.iteritems()
except AttributeError:
return itertools.izip(itertools.count(), d)
dd = {}
for k, v in hack(d):
dd.setdefault(v, []).append(k)
return dd
(It's the setdefault trick which is the important part.)
-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list