Николай обнови решението на 17.04.2012 23:16 (преди над 12 години)
+#!/usr/bin/env python3
+
+import os
+
+
+class BiDict:
+
+ def __init__(self, new_dict):
+ self.__check_init_type(new_dict)
+ self.__dict = new_dict
+ self.inverse()
+ self.inverse()
+
+ def __str__(self):
+ return self.__repr__()
+
+ def __repr__(self):
+ return 'BiDict(' + self.__dict.__str__() + ')'
+
+ def __len__(self):
+ return len(self.__dict)
+
+ def __setitem__(self, key, value):
+ self.__check_value_type_against_hash(value)
+ self.__take_care_of_duplicate_values(key, value, self.__dict)
+ self.__dict[key] = value
+
+ def __getitem__(self, key):
+ return self.__dict[key]
+
+ def inverse(self):
+ self.__dict = {v: k for (k, v) in self.__dict.items()}
+
+ def keys(self):
+ return self.__dict.keys()
+
+ def pop(self, key):
+ return self.__dict.pop()
+
+ def copy(self):
+ return BiDict(self.__dict.copy())
+
+ def update(self, new_dict):
+ self.__check_init_type(new_dict)
+ self.__check_values_are_hashable(new_dict)
+ self.__check_values_for_duplicates(new_dict)
+ self.__dict.update(new_dict)
+
+ def __check_init_type(self, new_dict):
+ if not isinstance(new_dict, dict):
+ my_type = type(new_dict)
+ raise TypeError('Type {0} is not supported'.format(my_type))
+
+ def __check_value_type_against_hash(self, value):
+ if not value.__hash__:
+ raise TypeError('Cannot set non-hashable value: {0}'.format(value))
+
+ def __take_care_of_duplicate_values(self, key, value, dictionary):
+ temp_key = self.__get_key_for_duplicate_value(value, dictionary)
+ if (not temp_key is None) and (not temp_key == key):
+ del self.__dict[temp_key]
+
+ def __get_key_for_duplicate_value(self, value, dictionary):
+ for key in dictionary.keys():
+ if dictionary.get(key) == value:
+ return key
+
+ def __check_values_are_hashable(self, new_dict):
+ for k in new_dict.keys():
+ self.__check_value_type_against_hash(new_dict.get(k))
+
+ def __check_values_for_duplicates(self, new_dict):
+ for key, val in new_dict.items():
+ self.__take_care_of_duplicate_values(key, val, new_dict)
+
+
+if __name__ == '__main__':
+ biDi = BiDict({'name': 'M', 'age': 'M', 'age': 'N'})
+ print(biDi)
+ d = {1: 'x', 2: 'y', 'c': 'c'}
+ biDi.update(d)
+ print(biDi)
+ biDi.inverse()
+ print(biDi)
+ t = biDi.copy()
+ t[1] = 'z'
+ print(biDi)
+ print(t)