因为自己实现,就根据 HashTable 的查找原理选择 List 作为数据存储结构,在每个位置放置一个子 List 用于解决 hash 冲突,因此对于构造函数来说,大概应该长这个样子
class MyDict:
def __init__(self, size=9999):
self.hash_list = [list() for _ in range(size)]
self.size = size
self.length = 0
def __setitem__(self, key, value):
"""添加key/value"""
hash_key = hash(key) % self.size
for item in self.hash_list[hash_key]:
if item[0] == key:
item[1] = value
break
else:
self.hash_list[hash_key].append([key, value])
self.length += 1
def __getitem__(self, key):
"""使用[key]方式获取值,key不存在时报错。"""
for item in self.hash_list[hash(key) % self.size]:
if item[0] == key:
return item[1]
raise KeyError(key)
def get(self, key, default=None):
"""使用get获取不到key时,不报错,给出默认值default"""
for item in self.hash_list[hash(key) % self.size]:
if item[0] == key:
return item[1]
return default
def __repr__(self):
"""打印字符串而不是对象"""
result = []
for sub_list in self.hash_list:
if not sub_list:
continue
for item in sub_list:
result.append(str(item[0]) + ": " + str(item[1]))
return "{" + ",".join(result) + "}"
def __contains__(self, key):
"""使用in时判断是否存在"""
for item in self.hash_list[hash(key) % self.size]:
if item[0] == key:
return True
return False
def __iterate_kv(self):
"""删除空的列表"""
for sub_list in self.hash_list:
if not sub_list:
continue
for item in sub_list:
yield item
def __iter__(self):
"""字典迭代时使用"""
for kv_pair in self.__iterate_kv():
yield kv_pair[0]
def keys(self):
"""获取所有的key,返回key组成的迭代器"""
return self.__iter__()
def values(self):
"""获取所有的value, 返回value组成的迭代器"""
for kv_pair in self.__iterate_kv():
yield kv_pair[1]
def items(self):
"""获取所有的kv—pair,返回value组成的迭代器"""
return self.__iterate_kv()
def __len__(self):
"""返回字典的长度"""
return self.length
my_dict = MyDict() # 定义一个字典
# 添加key-value键值对
my_dict["key1"] = "value1"
my_dict["key2"] = "value2"
my_dict["key3"] = ["value", "value"]
if "key1" in my_dict: # 使用in
print(my_dict.get("key1"))
print(my_dict["key2"])
# print(my_dict["不存在"])
print(my_dict.get("key3"))
print([i for i in my_dict.keys()])
print([i for i in my_dict.values()])
print([i for i in my_dict.items()])
print(len(my_dict))