Мирослав обнови решението на 19.04.2012 16:16 (преди над 12 години)
+class BiDict(dict):
+ def __init__(self, d):
+ for key, value in d.items():
+ self._check_mutable(value)
+ self._remove_duplicate_values(d)
+ dict.__init__(self, d)
+
+ def inverse(self):
+ d = dict()
+ for key, value in self.items():
+ d[value] = key
+ self.clear()
+ self.update(d)
+
+ def __setitem__(self, key, value):
+ self._check_mutable(value)
+ for skey, svalue in self.items():
+ if svalue is value:
+ del self[skey]
+ break
+ dict.__setitem__(self, key, value)
+
+ def update(self, d):
+ for key, value in d.items():
+ self._check_mutable(value)
+ dict.update(self, d)
+ self._remove_duplicate_values(self)
+
+ def _check_mutable(self, value):
+ if not type(value) in [tuple, int, float, complex, str, bool, frozenset]:
+ raise TypeError ("unhashable type: ", type(value))
+
+ def _remove_duplicate_values(self, d):
+ distinct = dict()
+ for key, value in d.items():
+ distinct[value] = key
+ d.clear()
+ for key, value in distinct.items():
+ d[value] = key
+