Clustering the keys of a dict according to its values
Mark Wooding
mdw at distorted.org.uk
Fri Nov 14 13:26:13 EST 2008
Florian Brucker <torf at torfbold.com> 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]
More information about the Python-list
mailing list