
Andre Delfino writes:
A dict method to retrieve the key of a value from a bijective dict would have come in handy to me in several occasions: [...] I do understand that retrieval wouldn't be O(1).
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. 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