python bijection

Joshua Bronson jabronson at gmail.com
Thu Nov 19 19:39:37 EST 2009


On Nov 19, 7:05 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> If I want a mapping a <-> b, I generally just create a dict {a:b, b:a}.
> What is the advantages or disadvantages of your code over the simplicity
> of the dict approach?

Well for one, you don't have to manually update the mapping from b ->
a if ever the mapping from a -> b changes. With your method you have
to write something like "d[a] = c; d[c] = a; del d[b]" instead of just
"d[a] = c", "del d[d.pop(a)]" instead of just "del d[a]", etc.

More significantly, your approach doesn't actually model a bijection
since there's no distinction between keys (the domain) and values (the
range). In other words, you lose information about which way is the
forward mapping and which is the inverse mapping. Worse, d.keys() and
d.values() would each give you the combination of your keys and
values, neither of which would be right, and d.items() would also
return twice as many elements as you expect with no way to distinguish
which side of the mapping a given pair comes from.



More information about the Python-list mailing list