Two mappings inverse to each other: f, g = biject()
Jonathan Fine
jfine at pytex.org
Tue Feb 6 08:34:14 EST 2007
Nick Vatamaniuc wrote:
> If you need to get a short name, given a long name or vice-verse _and_
> the set of short names and long names is distinct (it would be
> confusing if it wasn't!) then you can just have one dictionary, no
> need to complicate things too much:
> f[a]=b
> f[b]=a
> You won't know which is a short and which is a long based just on
> this, so you need to keep track of it. But it will give you the
> mapping.
Thank you for this suggestion, Nick. It's not
something I thought of. And I'm sure that in some
cases it might be just the right thing. It would
hold something like 'other-name' values. (Every
cat should have at least two names ...)
But for my application, I think it complicates the
code that uses the bijection.
For example, I want to say:
# Write the font dictionary to a file
for key in font_dict:
# write the font
# Does value already exist in the font dictionary?
# If not, add it to the font dictionary.
key = font_dict.inverse.get(value)
if key is None:
key = len(font_dict)
font_dict[key] = value
Following your suggestion, ingenious though it is,
would make the above code much more complicated and
error prone.
Perhaps it helps to think of
f, g = biject()
as establishing a database, that has a consistency
condition, and which has two views.
There we are: biject() gives two views on a
mapping (of a particular type). Thank you for
you suggestion - it has clarified my thinking.
--
Jonathan
More information about the Python-list
mailing list