Евгени обнови решението на 12.04.2012 11:47 (преди над 12 години)
+class BiDict(dict):
+ def __init__(self, *args):
+ dictionary = dict(*args)
+ for k, v in dictionary.items():
+ self[k] = v
+
+ def __setitem__(self, key, value):
+ if not value.__hash__:
+ raise TypeError("unhashable type: '{0}'".
+ format(type(value).__name__))
+
+ for k, v in self.items():
+ if v == value:
+ del self[k]
+ break
+
+ super(BiDict, self).__setitem__(key, value)
+
+ def __repr__(self):
+ return 'BiDict({0})'.format(super(BiDict, self).__repr__())
+
+ def update(self, E, **F):
+ if hasattr(E, 'keys'):
+ for k in E:
+ self[k] = E[k]
+ else:
+ for k, v in E:
+ self[k] = v
+
+ for k in F:
+ self[k] = F[k]
+
+ def copy(self):
+ return BiDict(super(BiDict, self).copy())
+
+ def setdefault(self, k, d=None):
+ if not d.__hash__:
+ raise TypeError("unhashable type: '{0}'".
+ format(type(d).__name__))
+ if k not in self:
+ self[k] = d
+ return d
+
+ def inverse(self):
+ old = self.copy()
+ self.clear()
+ for k, v in old.items():
+ super(BiDict, self).__setitem__(v, k)