Search code examples
pythonhashtablememory-address

How to print values instead of memory addresses for my hashtable? Python


I'm reading in package data from a csv to my hashtable and when I go to print the data to check if it's being inserted correctly, I'm getting the memory address of the values. It reads in the packageID and prints that piece correctly. I apologize for formatting the entire project in one file currently. I'm new to Python and how the files work together. When I have them split to separate files in Pycharm I couldn't tell what was being executed since it's dropdown menu would run a single file at a time (my guess)?

import csv
import math


####################################################################################################################

class hashtable:
    # Set initial capacity of the Hashtable to 40 and sets the buckets to empty.
    def __init__(self, initial_capacity=40):
        # initialize the hash table with empty bucket list entries.
        self.table = []
        for i in range(initial_capacity):
            self.table.append([])

    # Inserts new key:value pair into desired bucket.
    def insert(self, key, item):  # does both insert and update
        # get the bucket list where this item will go.
        bucket = hash(key) % len(self.table)
        bucket_list = self.table[bucket]
        key_value = [key, item]
        bucket_list.append(key_value)
        return True

    # Searches for the package using its packageID as the key and returns it if found.
    def search(self, key):
        # get the bucket list where this key would be.
        bucket = hash(key) % len(self.table)
        bucket_list = self.table[bucket]
        # print(bucket_list)

        # search for the key in the bucket list
        for kv in bucket_list:
            # print (key_value)
            if kv[0] == key:
                return kv[1]  # value
        return None

    # Removes a package with the matching key.
    def remove(self, key):
        # get the bucket list where this item will be removed from.
        bucket = hash(key) % len(self.table)
        bucket_list = self.table[bucket]

        # remove the item from the bucket list if it is present.
        for kv in bucket_list:
            # print (key_value)
            if kv[0] == key:
                bucket_list.remove([kv[0], kv[1]])


####################################################################################################################

class Package:
    def __init__(self, ID, Address, City, State, Zip, Deadline, Weight, Notes, Status, Deliverytime):
        self.packageID = ID
        self.packageAddress = Address
        self.packageCity = City
        self.packageState = State
        self.packageZip = Zip
        self.packageDeadline = Deadline
        self.packageWeight = Weight
        self.packageNotes = Notes
        self.packageStatus = Status
        self.deliveryTime = Deliverytime


#####################################################################################################################


def loadPackageData(fileName):
    with open(fileName) as Package_List:
        packageData = csv.reader(Package_List, delimiter=',')
        for package in packageData:
            pID = int(package[0])
            pAddress = package[1]
            pCity = package[2]
            pState = package[3]
            pZip = package[4]
            pDeadline = package[5]
            pWeight = package[6]
            pNotes = package[7]
            pStatus = "At hub"
            pDeliverytime = "00:00"

            #package object
            p = Package(pID, pAddress, pCity, pState, pZip, pDeadline, pWeight, pNotes, pStatus, pDeliverytime)
            #print (p)

            # insert into the hash table
            myHash.insert(pID, p)

# Hash table instance
myHash = hashtable()

# Load packages to Hashtable
loadPackageData('packageData.csv')

print("Packages from Hashtable:")
print(myHash.table)
# Fetch data from hashtable
#for i in range (len(myHash.table)+1):
#    print("Package: {}".format(myHash.search(i+1))) # 1 to 40 sent to myHash.search()

When print(myHash.table) is called I get output structured like this except for all 40 packages.

[[[40, <__main__.Package object at 0x000001E1489114C0>]], [[1, <__main__.Package object at 0x000001E148914220>]], [[2, <__main__.Package object at 0x000001E148911DF0>]], [[3, <__main__.Package object at 0x000001E148911D00>]]

I couldn't understand how to implement another post asking a similar question with my project so I am here now. I really appreciate all of you for any help!


Solution

  • You must override __repr__ and __str__ methods for class to be able print what you need.

    In other way you may add own human_readable-like property

    class PackageA:
      def __init__(self, ID, Address, City, State, Zip, Deadline, Weight, Notes, Status, Deliverytime):
        self.packageID = ID
        self.packageAddress = Address
        self.packageCity = City
        self.packageState = State
        self.packageZip = Zip
        self.packageDeadline = Deadline
        self.packageWeight = Weight
        self.packageNotes = Notes
        self.packageStatus = Status
        self.deliveryTime = Deliverytime
    
    class PackageB:
      def __init__(self, ID, Address, City, State, Zip, Deadline, Weight, Notes, Status, Deliverytime):
        self.packageID = ID
        self.packageAddress = Address
        self.packageCity = City
        self.packageState = State
        self.packageZip = Zip     
        self.packageDeadline = Deadline
        self.packageWeight = Weight
        self.packageNotes = Notes
        self.packageStatus = Status
        self.deliveryTime = Deliverytime
    
      def __str__(self):
        return f'STR is <{self.packageID} {self.packageAddress} {self.packageCity} {self.packageState} {self.packageZip} {self.packageDeadline} {self.packageWeight} {self.packageNotes} {self.packageStatus} {self.deliveryTime}>'
    
      def __repr__(self):
        return f'REPR is <{self.packageID} {self.packageAddress} {self.packageCity} {self.packageState} {self.packageZip} {self.packageDeadline} {self.packageWeight} {self.packageNotes} {self.packageStatus} {self.deliveryTime}>'
    
      @property
      def human_readable(self):
        return f'Readable representation is <{self.packageID} {self.packageAddress} {self.packageCity} {self.packageState} {self.packageZip} {self.packageDeadline} {self.packageWeight} {self.packageNotes} {self.packageStatus} {self.deliveryTime}>'
    
    packagesA = []
    packagesB = []
    
    for i in range(0,3):
      packagesA.append(PackageA(f"ID{i}", f"Address{i}", f"City{i}", f"State{i}", f"Zip{i}", f"Deadline{i}", f"Weight{i}", f"Notes{i}", f"Status{i}", f"Deliverytime{i}"))
      packagesB.append(PackageB(f"ID{i}", f"Address{i}", f"City{i}", f"State{i}", f"Zip{i}", f"Deadline{i}", f"Weight{i}", f"Notes{i}", f"Status{i}", f"Deliverytime{i}"))
    
    
    print(packagesA)
    print("--")
    print(packagesB)
    print("--")
    print([str(x) for x in packagesB])
    print("--")
    print([x.human_readable for x in packagesB])
    

    Output:

    [<__main__.PackageA object at 0x104ca0710>, <__main__.PackageA object at 0x104ca0a90>, <__main__.PackageA object at 0x104ca0e10>]
    --
    [REPR is <ID0 Address0 City0 State0 Zip0 Deadline0 Weight0 Notes0 Status0 Deliverytime0>, REPR is <ID1 Address1 City1 State1 Zip1 Deadline1 Weight1 Notes1 Status1 Deliverytime1>, REPR is <ID2 Address2 City2 State2 Zip2 Deadline2 Weight2 Notes2 Status2 Deliverytime2>]
    --
    ['STR is <ID0 Address0 City0 State0 Zip0 Deadline0 Weight0 Notes0 Status0 Deliverytime0>', 'STR is <ID1 Address1 City1 State1 Zip1 Deadline1 Weight1 Notes1 Status1 Deliverytime1>', 'STR is <ID2 Address2 City2 State2 Zip2 Deadline2 Weight2 Notes2 Status2 Deliverytime2>']
    --
    ['Readeable representation is <ID0 Address0 City0 State0 Zip0 Deadline0 Weight0 Notes0 Status0 Deliverytime0>', 'Readeable representation is <ID1 Address1 City1 State1 Zip1 Deadline1 Weight1 Notes1 Status1 Deliverytime1>', 'Readeable representation is <ID2 Address2 City2 State2 Zip2 Deadline2 Weight2 Notes2 Status2 Deliverytime2>']