
I've had use cases for this, and written a class to do it (using Stephen's two dict approach. I'd be really surprised if there wasn't one on PyPi --the trick is to know what to call it to search for it. Now that I think about it -- my use case was many-to-many, not one to one -- so not quite the same -- each value was a list associated with a given key -- and vice versa. I think it would be a bad idea to overload the built in dict with anything like this. *maybe* a new class for the collections module, if you can find a good well respected implementation, and folks can agree on what's wanted (performance characteristics, API, etc..) -- that's a pretty tall order though. If O(log N) is good enough and bijectivity is guaranteed by some other
mechanism, a bisection search on d.items() with key=lambda x: x[1] does the trick.
You'd also have to keep it sorted by value. So now you are guaranteeing bijectivity and keeping it sorted -- I'd just use two dicts :-) Though then the values would have to be hashable, so there's that. -CHB
If you know the dict is supposed to be one-to-one and the keys and values are disjoint sets, as in your example, just
def bijective_add(d, k, v): if k in d and d[k] != v: raise BijectiveDictValueChangeError d[k] = v d[v] = k
gives O(1) both ways. Maybe you need some kind of check to be sure you're retrieving the right type for the calling code.
Otherwise you can pair two dicts in a class and endow it with your inverse method. I would do the check for bijectivity on addition (as above) rather than on retrieval, though.
If you really want to save the space, you can add an additional hashtable for the values in a C module, but it's not clear to me that any particular choice for bijectivity checks would be universally desirable in applications so that seems premature.
So I think you need to make clear what your goals are since there are at least four solutions with varying performance characteristics. I'm agnostic on whether a dict type which guarantees bijectivity would be a good addition. The mathematician in me wants it, but my experience says the dict pair is good enough, YAGNI (for values of "you" == "me", anyway).
Regards, Steve _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/5EEE27... Code of Conduct: http://python.org/psf/codeofconduct/
-- Christopher Barker, PhD (Chris) Python Language Consulting - Teaching - Scientific Software Development - Desktop GUI and Web Development - wxPython, numpy, scipy, Cython