首页 > 解决方案 > 如何向 HashMap 添加键/值?

问题描述

class HashMap:
    def __init__(self):
        self.max_length = 8
        self.max_load_factor = 0.8
        self.length = 0
        self.map = [None] * self.max_length

    def get(self, key, default):
        value = dict.get(key, default)
        return value  # returns the value for key if key is in the dictionary, else
                      # default. If default is not given, it defaults to none.

    def set(self, key, value):
        #need to add the key value pair into the hashmap
        #if self.max_load_factor >= .8:
            #refresh the map into a map double the capacity

所以我能够get()为我的 hashmap 输入方法,这相对简单(如果键在字典中,则返回键的值,等等……)但是如何将键值对添加到 hashmap 本身?

有人能指出我正确的方向吗?我需要将其添加到self.map实例中吗?

标签: pythonclass

解决方案


您没有向我们展示您如何尝试使用它,而且我看不到您dict在任何地方定义。但我想我看到了你想要的东西,比如

class HashMap:
    def __init__(self):
        self.dict = {}

    def get(self, key, default=None):
        return self.dict.get(key, default)

    def set(self, key, value):
        self.dict[key] = value

if __name__ == '__main__':
    hm = HashMap()
    hm.set('test', 'hello, world')
    print(hm.get('test'))

应该这样做(和输出)

hello, world

推荐阅读