Kam Kam - 1 month ago 6
Python Question

Retrieving attributes of objects stored in dictionary

class Customer:
def __init__(self,custid,name,addr,city,state,zipcode):
self.custid=custid
self.name=name
self.addr=addr
self.city=city
self.state=state
self.zipcode=zipcode
self.memberLevel=BasicMember()
self.monthlySpending =0


Well i am able to read a file and then split it such that in dictionary key is my customerid and value is the customer object. But i can't retrieve the attributes for each object stored in my dictionary. How to get each objects attributes from dictionary.

for line in open('customers.dat','r'):
item=line.rstrip(',')
intput =line.split(',')
cc=Customer.Customer(*intput)
s2=item.split(',',1)[0]
d[s2]=[cc]


sample data of customer is :

619738273,Admiral Ackbar,383 NeiMoidian Road,Utapau,MA,01720
118077058,Padme Amidala,846 Amani Road,D'Qar,MA,01508
360513913,Wedge Antilles,700 NeiMoidian Road,D'Qar,MA,01508


while my output after storing each object in dictionary is :

{'739118188': [<Customer.Customer object at 0x005FF8B0>],
'578148567': [<Customer.Customer object at 0x005FF9B0>]}


So how to get attributes for the object stored in the dictionary.

Answer

I'm not sure why you wrapped each one in a list, but simply access them as normal:

>>> d['619738273'][0].name
'Admiral Ackbar'

I'd recommend not wrapping each one in a list:

d[s2] = cc

Then you don't need the [0]:

>>> d['619738273'].name
'Admiral Ackbar'

You can also streamline the parsing step:

with open('customers.dat') as f:
    for line in f:
        k,*data = line.split(',')
        d[k] = Customer.Customer(k, *data)

Although it'd be better to use csv, since it looks like you're working with a CSV file:

import csv
with open('customers.dat') as f:
    reader = csv.reader(f)
    for k,*data in reader:
        d[k] = Customer.Customer(k, *data)
Comments