Worthwhile to reverse a dictionary
Mike Meyer
mwm at mired.org
Wed Jan 4 17:55:22 EST 2006
crc <crc.214rin at no-mx.forums.yourdomain.com.au> writes:
> I assume your talking about building a new dictionary with the key and
> value pair switched. I have seen no built in function to do this but I
> have found a way to create another dictionary that is the inverse of
> the first.
Note that you can't reliable "reverse" a dictionary. That's because
you can put anything in a dictionary, but some things can't be used as
keys to a dictionary.
> when your redy to build a revers dictionary you semply do the folowing
> b={}
> for x in a:
> temp_idx=a[x]
> b[temp_idx]=x
You can do it with a single list comprehension:
b = dict([(x, y) for y, x in a.iteritems()])
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list