Home > front end >  How do you append objects in a hash table with the name of the objects as the key?
How do you append objects in a hash table with the name of the objects as the key?

Time:10-14

I am relatively new to Python and I need help with implementing Hash table class using Pythons built-in dictionary and appending objects of a file to the hash table and store the name of the objects as key.

I want to read my file(which contains names, phone numbers and email addresses), make objects and add them to the hash table with the name as the key. I tried this:

with open("names.csv", "r") as names_file:
    for line in names_file.readlines():
        person = Person(line)
        q = HashtableDict(1000)
        q.store(key=person.name, data=person)

However, it doesn't seem to work when trying to search for a key(name) with the find method which means that something went wrong with storing the objects to the hash table. How can this be fixed?

CodePudding user response:

You are creating hash table per line in csv.

You need to create it only once

q = HashtableDict(1000)

with open("names.csv", "r") as names_file:
    for line in names_file.readlines():
        person = Person(line)
        q.store(key=person.name, data=person)

CodePudding user response:

You are re-creating a new HashtableDict for each line in the csv.

After the entire loop, you are left with the last created HashtableDict as q. It will only contain the name of the last person.

  • Related