This article mainly introduces how to use the zipper method to implement dictionary in python. The article provides detailed sample code, which is of reference value to everyone, if you need it, let's take a look. This article mainly introduces how to use the zipper method to implement dictionary in python. The article provides detailed sample code, which is of reference value to everyone, if you need it, let's take a look.
Preface
A dictionary is also called a discrete list. The greatest feature is that it uses keys to find its corresponding values. its time complexity is O (1 ), the following article introduces how to implement the dictionary using the zipper method in python.
In Python, how does one use a list to implement a dictionary?
The biggest problem with dictionary implementation by list is to solve the hash conflict. what should I do if the same location is obtained by calculating different keys in the list?
The simplest way is to use the zipper method.
Class MyDict: def init (self, num = 100): # specify the list size self. _ num = num self. _ lst = [] for _ in range (self. _ num): self. _ lst. append ([]) def update (self, key, value): # add key-value key_index = hash (key) % self. _ num for I, (k, v) in enumerate (self. _ lst [key_index]): if key = k: self. _ lst [key_index] [I] = [key, value] break else: self. _ lst [key_index]. append ([key, value]) def get (self, key): # pop-up value key_index = hash (key) % self based on the specified key. _ num for k, v in self. _ lst [key_index]: if k = key: return v else: raise KeyError ('No such {} key '. format (key) def pop (self, key): # Based on the key pop-up element and delete key_index = hash (key) % self. _ num for I, (k, v) in enumerate (self. _ lst [key_index]): if k = key: result = v self. _ lst. pop (I) return result else: raise KeyError ('No such {} key '. format (key) def getitem (self, key): # you can use subscript to set key_index = hash (key) % self. _ num for k, v in self. _ lst [key_index]: if k = key: return v else: raise KeyError ('No such {} key '. format (key) def keys (self): # obtain all keys for index in range (self. _ num): for k, v in self. _ lst [index]: yield k def values (self): # obtain all values for index in range (self. _ num): for k, v in self. _ lst [index]: yield v def items (self): # retrieve all entries for index in range (self. _ num): for item in self. _ lst [index]: yield item
Time found by key, visible
The above is a detailed description of the sample code of the dictionary method using the zipper method in python. For more information, see other related articles in the first PHP community!