Tell us what’s happening:
I need help with 16. HashTable().add(‘dear’, ‘friend’) and HashTable().add(‘read’, ‘book’) should add both the key-value pairs to the collection at index 412 as a nested dictionary.
I suspect it may have to do with the def add if statement but i cant quite put it together on what to do to ensure both are added as a nested dictionary.
Your code so far
class HashTable:
def __init__(self):
self.collection = {}
def hash(self, key):
if not isinstance(key, str):
return('Key must be a string')
hash_value = 0
for char in key:
hash_value += ord(char)
return hash_value
def add(self, key, value):
hash_value = self.hash(key)
if hash_value not in self.collection:
self.collection[hash_value] = {}
self.collection[hash_value][key] = value
def remove(self, key):
key_hash = self.hash(key)
if key_hash in self.collection:
if key_hash in self.collection[key_hash]:
del self.collection[key_hash][key]
return
def lookup(self, key):
hash_value = self.hash(key)
if hash_value in self.collection and key in self.collection[hash_value]:
return self.collection[hash_value][key]
return None
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36
Challenge Information:
Build a Hash Table - Build a Hash Table