Христо обнови решението на 18.04.2012 14:22 (преди над 12 години)
+class BiDict():
+ @classmethod
+ def fromkeys(self, seq, value=None):
+ return dict.fromkeys(seq, value)
+
+ def __init__(self, data):
+ self._data = dict()
+ self._inv = dict()
+ self.update(data)
+ #self._data = dict(data.items())
+ #self._inv = dict(zip(self._data.values(), self._data.keys()))
+
+ def __getitem__(self, key):
+ return self._data[key]
+
+ def __setitem__(self, key, value):
+ if value.__hash__ :
+ if value in self._inv.keys():
+ old = self._data[key]
+ del self._data[self._inv[value]]
+ del self._inv[old]
+ self._data[key] = value
+ self._inv[value] = key
+ else:
+ raise TypeError ("unhashable type: '"+ type(value).__name__+"'")
+
+ def __delitem__(self, key):
+ del self._data[key]
+ for k in self._inv.keys():
+ if (self._inv[k] == key):
+ key = k
+ break
+ del self._inv[key]
+
+ def __contains__ (self, key):
+ return key in self._data
+
+ def __eq__ (self, other):
+ if not other.__len__:
+ return False
+
+ print(len(self))
+ print(len(other))
+
+ if len(other) != len(self):
+ return False
+
+ for k,v in self.items():
+ if not other.__contains__(k):
+ return False
+ if other[k] != v:
+ return False
+ return True
+
+ def __ne__ (self, other):
+ return not self.__eq__(other)
+
+ def __len__(self):
+ return self._data.__len__()
+
+ def __str__(self):
+ return self._data.__str__()
+
+ def __repr__(self):
+ return self.__str__()
+
+ def __iter__(self):
+ return self.iterkeys()
+
+ def clear(self):
+ self._data.clear()
+ self._inv.clear()
+
+ def copy(self):
+ return BiDict(self._data)
+
+ def get(self, key, default=None):
+ if not key in self.keys():
+ return default
+ return self._data[key]
+
+ def items(self):
+ return zip(self.keys(), self.values())
+
+ def iterkeys(self):
+ return self._data.iterkeys()
+
+ def iteritems(self):
+ return self._data.iteritems()
+
+ def itervalues(self):
+ return self._data.itervalues()
+
+ def keys(self):
+ return self._data.keys()
+
+ def values(self):
+ return self._data.values()
+
+ def inverse(self):
+ buf = self._data
+ self._data = self._inv
+ self._inv = buf
+
+ def pop(self, key, default=None):
+ value = self.get(key)
+ if value is not None:
+ del self[key]
+ return value
+ if default is not None:
+ return default
+ else:
+ raise KeyError('Key not found')
+
+ def popitem(self):
+ if len(self) == 0:
+ raise KeyError('Dictionary is empty')
+
+ for k in self.keys():
+ key = k
+ break
+ return self.pop(key)
+
+ def update(self, dict, *args, **kwargs):
+ for k, v in dict.items():
+ self[k] = v
+ for k,v in kwargs.items():
+ self[k] = v
+
+ def setdefault(self, key, default=None):
+ if key in self:
+ return self[key]
+ self[key] = default
+ return default