Илиян обнови решението на 19.04.2012 17:52 (преди над 12 години)
+class BiDict(dict):
+ def __init__(self):
+ super(BiDict,self).__init__()
+
+ def __init__(self,something):
+ '''
+ something can be mapping or iterable see help(dict)
+ '''
+ if isinstance(something,dict):
+ mapping=something.items()
+ else:
+ mapping=something
+ bidict=self.__make_bidict(mapping)
+ super(BiDict,self).__init__(bidict)
+
+ def __make_bidict(self,mapping):
+ '''
+ Takes [(a1,b1),(a2,b2),...]
+ '''
+
+ keys_values={}
+ values_keys={}
+ return_dict={}
+ for k,v in mapping:
+ if k in values_keys:
+ values_keys.pop(k)
+ if v in keys_values:
+ keys_values.pop(v)
+
+ keys_values[k]=v
+ values_keys[v]=k
+
+
+ for v,k in values_keys.items():
+ if not v in keys_values:
+ return_dict[values_keys[v]]=keys_values[k]
+
+
+ return return_dict
+
+ def inverse(self):
+ reversed={}
+ for k,v in self.items():
+ reversed[v]=k
+
+ self.clear()
+ #self.update(reversed)
+ super(BiDict,self).update(reversed)
+
+ def update(self,E,**F):
+ bidict_e=self.__make_bidict(dict(E).items())
+ super(BiDict,self).update(bidict_e)
+
+ bidict_e.update(self.__make_bidict(dict(**F).items()))
+ super(BiDict,self).update(bidict_e)
+
+ new_bidict=self.__make_bidict(self.items())
+ self.clear()
+ super(BiDict,self).update(new_bidict)
+
+
+ def __setitem__(self,key,value):
+ self.update({key:value})