python - 如何向 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
实例中吗?
解决方案
您没有向我们展示您如何尝试使用它,而且我看不到您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
推荐阅读
- git - 我分支了错误的分支,如何将更改移动到正确的分支?
- python - 同时控制步进电机和相机
- bash - Bash 脚本自动回答命令
- javascript - 如何在 Hightcharts / Highstock 中获取隐藏系列的数据?
- arrays - 如何从 findOne Mongoose 获取对象内部的数组
- batch-file - 在睡眠事件上运行脚本
- r - nchar(desc) 中的错误:无效的多字节字符串,使用 map() 和 rvest 时网页抓取时的元素 1
- python - 如何删除数据类属性
- java - ListView 中的 Wicket 表单组件值更改会影响所有元素
- sql-server - 基于参数值的条件格式