Reverting (key, value) pairs in a dictionary

Alex Martelli aleax at aleax.it
Fri Oct 31 03:44:03 EST 2003


Shu-Hsien Sheu wrote:

> How do you turn a dictionary of <original_key>: <original_value> into
> <original_value>: <original_key>, when there is no duplicate values?

If, as per this spec, each key was mapped to one hashable value (but your
example below indicates this isn't the case!), then

newkk = dict([ (v,k) for k, v in kk.iteritems() ])

would be the solution.  But for your example:

> For instance, I have a dictionary kk:
> kk = {'abc': ['B', 'C', 'D', 'E'], 'def':['G', 'H']}
> 
> and I want a new dictionary newkk which looks like:
> newkk = {'B':'abc', 'C':'abc', 'D':'abc', 'E':'abc', 'G':'def', 'H':'def'}

you need a nested loop on each so-called value (==list of values), so:

newkk = dict([ (v,k) for k, vs in kk.iteritems() for v in vs ])


In python 2.4 (will be a while coming, so DON'T hold your breath) you can
spell this without those annoying extra square brackets in ([ ... ]) and
get a tiny speedup as well as marginally clearer syntax.


Alex





More information about the Python-list mailing list