'inverting' a dict

Raymond Hettinger python at rcn.com
Thu Jan 1 05:40:45 CET 2004


Irmen de Jong <irmen at -NOSPAM-REMOVETHIS-xs4all.nl> wrote in message news:<3ff2cba6$0$316$e4fe514c at news.xs4all.nl>...
> Wade Leftwich wrote:
> 
> > def invert_dict(D):
> >     return dict([(y,x) for (x,y) in D.items()])
> 
> No, this one only works for non-sequence-type values.
> I wanted to map every item of a value (a sequence)
> to the corresponding key.
> 
> --Irmen

Try a nested list comprehension:

>>> data = { "key1": ("value1", "value2"), "key2": ("value3",) }
>>> dict([(v,k) for k,vlist in data.iteritems() for v in vlist])
{'value3': 'key2', 'value2': 'key1', 'value1': 'key1'}


Raymond Hettinger

P.S.  In Py2.4, it will be possible to write this without the
brackets.  The resulting generator expression is faster and more
memory friendly:

>>> dict((v,k) for k,vlist in data.iteritems() for v in vlist)
{'value3': 'key2', 'value2': 'key1', 'value1': 'key1'}



More information about the Python-list mailing list