Worthwhile to reverse a dictionary

Alex Martelli aleax at mail.comcast.net
Sun Jan 8 01:49:05 EST 2006


Mike Meyer <mwm at mired.org> wrote:

> 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.

That's reason #1.  Reason #2 is that you can have duplicates among a
dict's values, but not among its keys.  So, a simply and correctly
reversable dict is one whose values are all hashable and unique -- in
terms of EQUALITY (which is stricter than demanding uniqueness in terms
of IDENTITY), e.g. you can't have both 1 (the integer) and 1.0 (the
float with a 0 fractional part) as values (because they're not distinct
by equality: 1 == 1.0).

If you do have a dict whose hashable values are not guaranteed to be
unique you have several choices as to how to "pseudo-reverse" it (e.g.,
"dropping", among the values in the pseudoreversed dict, all but one of
the keys that map to the same value in the original dict; or, making a
"reversoid" dict whose values are containers of all the keys mapping to
each value in the original dict).

If you have a dict whose values are not guaranteed to be hashable, and
thus can't be keys in the ``sotospeakreverse'' dict, you have to work
even harder, striving to build keys for the latter which may in some
sense (probably one meaningful only to a specific application) "stand
for" the values in the original dict.  I remember only one case in a
real-world program of needing anything like that -- the original dict
had "sub"-dicts (mapping strings to numbers) as values, but fortunately
it was acceptable for the application to have frozen sets of (key,
value) pairs "stand for" those subsets in the "reversoid" dict (I sure
did wish at the time I had "frozen dicts", though;-).


Alex



More information about the Python-list mailing list