Петър обнови решението на 19.04.2012 14:40 (преди над 12 години)
+import collections
+
+
+class BiDict(dict):
+
+ def __init__(self, dictionary):
+ dict.__init__(self, dictionary)
+ self.__check_values()
+
+ def __check_values(self):
+ self.inverse()
+ self.inverse()
+
+ def __check_for_hashable(self, value):
+ if not isinstance(value, collections.Hashable):
+ raise TypeError("unhashable type: " + type(value).__name__)
+
+ def inverse(self):
+ inversed = {v: k for k, v in self.items()}
+ self.clear()
+ self.update(inversed)
+
+ def __setitem__(self, key, value):
+ print(value)
+ self.__check_for_hashable(value)
+ if value in self.values():
+ self.inverse()
+ del self[value]
+ self.inverse()
+ dict.__setitem__(self, key, value)
+
+ def update(self, *args, **kwargs):
+ dictionary = dict(*args, **kwargs)
+ for value in dictionary.values():
+ self.__check_for_hashable(value)
+ dict.update(self, *args, **kwargs)
+
+ def setdefault(self, key, value=None):
+ self.__check_for_hashable(value)
+ dict.setdefault(self, key, value)