Python zipper method and open address method to achieve dictionary


Python dictionary is the most flexible built-in data structure type in Python besides list. Lists are ordered combinations of objects,A dictionary is an unordered collection of objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.

Using subscript index in the list can quickly get the corresponding value, so we need to do two things:

  • How to calculate a unique value for a key
  • How to distribute the unique value uniformly and uniquely in a fixed length list

How to calculate a unique value for a key

Because the key of the dictionary is immutable and hashable, we can use the hash function to calculate the unique hash value corresponding to the key.

How to distribute the unique value uniformly and uniquely in a fixed length list

Hash is an algorithm that can map large data sets to fixed length data sets, so we can hash the hash values calculated above. It’s obvious that there will be hash conflicts after hashing. Therefore, we need to deal with this kind of conflict, once the unique value can be evenly and uniquely distributed. At this time, there are two ways to deal with hash conflict: zipper method and open address method


Zipper method

The hash address of thek,vThe pairs are placed in the same single linked list. Here are two functions

  • putFunction:put(slots, key, value)To insert data into the dictionary
  • getFunction:get(slots, key)To read data from a dictionary.

You can also implement more functions, such asdict.keys()

#!/usr/bin/env python
# coding=utf-8

slots = []
slotsNum = 32
for _ in range(32):

def put(slots, key, value):
    i = hash(key) % slotsNum
    pos = -1
    for pos, (k, v) in enumerate(slots[i]):
        if key == k:
        slots[i].append((key, value))
    if pos >= 0 and pos < len(slots[i]):
        slots[i][pos] = (key, value)

def get(slots, key):
    i = hash(key) % slotsNum
    for k, v in slots[i]:
        if key == k:
            return v
        Raise keyerror (key) ා throws an exception when it does not exist

put(slots, 'a', 1)
print(get(slots, 'a'))
put(slots, 'b' ,2)
print(get(slots, 'b'))
put(slots, 'a', 3)
print(get(slots, 'a'))

We will encapsulate these two functions into classes

class Dict:
    def __init__(self, num):
        self.__solts__ = []
        self.num = num
        for _ in range(num):

    def put(self, key, value):
        i = hash(key) % self.num
        for p, (k, v) in enumerate(self.__solts__[i]):
            if k == key:
            self.__solts__[i].append((key, value))
        self.__solts__[i][p] = (key, value)

    def get(self, key):
        i = hash(key) % self.num
        for k, v in self.__solts__[i]:
            if k == key:
                return v
        raise KeyError(key)

    #Keys function
    def keys(self):
        ret = []
        for solt in self.__solts__:
            for k, _ in solt:
        return ret

After being encapsulated as a class, the method and thedictIt’s more like that

Open address method

The open address method is used to deal with hash conflicts in Python dictionary internal implementation, which will be supplemented later

Remember to praise me!

We have carefully arranged video courses and e-books from entry-level, advanced and practical in all directions of computer. We can always find the learning materials you need according to the reasonable classification of the catalogue. What are you waiting for? Pay attention to download it!!!

Python zipper method and open address method to achieve dictionary

If you don’t forget, there will be an echo. Please give me a compliment. Thank you very much.

I am a bright brother in the workplace, YY Senior Software Engineer, with four years of working experience. I refuse to be a leading slash programmer.

Listen to me, more progress, a shuttle of procedural life

If you are lucky enough to help you, please give me a “like” to pay attention to it. If you can comment on it and give me encouragement, I will be very grateful.

List of articles of workplace bright brother:More articles

Python zipper method and open address method to achieve dictionary

All my articles and answers have cooperation with the copyright protection platform. The copyright belongs to brother Liang in the workplace. Without authorization, reprint must be investigated!