Create dictionary of objects

Question:

I want to create a class dictionary that will have client id as the key and object of my class as the value. I want to get the object of my class by using client id as key.

id_iter = itertools.count()

def __init__(self):
    self.cl_id = 0
    self.surname = ""
    self.name = ""
    self.phone = ""
    self.address = ""
    self.email = ""
    self.afm = ""

def enter_client_info(self):
    self.cl_id = next(self.id_iter)
    self.surname = input("Enter client surname: ")
    self.name = input("Enter client name: ")
    self.phone = input("Enter client phone: ")
    self.address = input("Enter client address: ")
    self.email = input("Enter client email: ")
    self.afm = input("Enter client afm: ")

My ultimate purpose is to be able to call each client’s class attribute like
cl_list([cl_id].name),cl_list([cl_id].surname),etc.

I tried the code below but it gives the last added value to every key.

client_new = Client()
client_new.enter_client_info()
print(client_new.cl_id)
cl_list[client_new.cl_id] = client_new

client_new.enter_client_info()
print(client_new.cl_id)
cl_list[client_new.cl_id] = client_new

print(cl_list[1].name)
print(cl_list[2].surname)

This little client database is my first try to learn by creating code. Any help or hint would be appreciated!

Asked By: DarkSide

||

Answers:

The problem is that you re-use the old Client object instead of calling client_new = Client() a second time. Python doesn’t copy objects unless you explicitly tell it to, so when you do cl_list[client_new.cl_id] = client_new that means the dictionary now has an entry pointing to the same object as client_new. When you add it to another entry, that is still the same object.

client_new = Client()
client_new.enter_client_info()
print(client_new.cl_id)
cl_list[client_new.cl_id] = client_new

client_new = Client()  # <--- this line is new
client_new.enter_client_info()
print(client_new.cl_id)
cl_list[client_new.cl_id] = client_new

print(cl_list[1].name)
print(cl_list[2].surname)
Answered By: Jasmijn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.