Габриела обнови решението на 19.04.2012 02:01 (преди над 12 години)
+class BiDict:
+ """BiDict: dict that can be inversed"""
+
+ def __init__(self, *args, **kwargs):
+ src = dict(*args, **kwargs)
+ for value in src.values():
+ if not value.__hash__: #bool(None) == False
+ raise TypeError("unhashable type: '%s'" \
+ % value.__class__.__name__)
+ self.dict = {}
+ for key in src:
+ if src[key] not in self.dict.values():
+ self.dict[key] = src[key]
+ self.index = 0
+
+ def __repr__(self):
+ return "BiDict(" + str(self.dict) + ")"
+
+ #required string representation matches __repr__
+ __str__ = __repr__
+
+ def __setitem__(self, key, value):
+ if value in self.dict.values():
+ self.dict.__delitem__(key)
+ self.dict[key] = value
+
+ def update(self, E, **F):
+ dict_source = {}
+ dict_source.update(E, **F)
+ self = BiDict(dict_source)
+
+ def inverse(self):
+ self.dict = {v: k for (k, v) in self.dict.items()}
+
+ #standard stuff
+ def __getitem__(self, key):
+ return self.dict[key]
+
+ def __contains__(self, key):
+ return self.dict.__contains__(key)
+
+ def __delitem__(self, key):
+ self.dict.__delitem__(key)
+
+ def __eq__(self, other):
+ return self.dict == other.dict
+
+ def __iter__(self):
+ return self.dict.__iter__()
+
+ def __reduce__(self):
+ raise TypeError("can't pickle BiDict objects")
+
+ __reduce_ex__ = __reduce__
+
+ def clear(self):
+ self.dict.clear()
+
+ def copy(self):
+ return self.dict.copy()
+
+ def fromkeys(self, *args, **kwargs):
+ return self.dict.fromkeys(*args, **kwargs)
+
+ def get(self, *args, **kwargs):
+ return self.dict.get(*args, **kwargs)
+
+ def items(self):
+ return self.dict.items()
+
+ def keys(self):
+ return self.dict.keys()
+
+ def pop(self, *args, **kwargs):
+ return self.dict.pop(*args, **kwargs)
+
+ def popitem(self):
+ return self.dict.popitem()
+
+ def setdefault(self, *args, **kwargs):
+ return self.dict.setdefault(*args, **kwargs)
+
+ def values(self):
+ return self.dict.values()