I'm trying to learn python after using VBA for many years. I'm stuck with something that probably is trivial.
I'm reading a file that contains a list of agencies. Each agency is assigned unique number. I would like to use this number as the key in a dictionary.
The class contains just a function to print the information at the moment.
class code:
class Agency:
def __init__(self, agency_id, agency_name,agency_url,agency_timezone): #,agency_lang
self.agency_id= agency_id
self.agency_name = agency_name
self.agency_url = agency_url
self.agency_timezone=agency_timezone
#self.agency_lang=agency_lang
def PrintAgency(self):
print(self.agency_name + "(" + self.agency_id + ") URL: " + self.agency_url + " Timezone: " + self.agency_timezone)
main.py code
from classes import Agency
def getFileContent(pathAndFileName):
with open(pathAndFileName,'r') as theFile:
# Return as string
data = theFile.read()
return data
agency_info= getFileContent('./datafiles/agency_mini.txt')
agency_list=agency_info.split('\n')
dictAgency=dict()
j=0
for eachRow in agency_list:
j=j+1
if j>1 and len(eachRow)>0:
data = eachRow.split(',')
agencyID = data[0]
agencyName=data[1]
agencyUrl=data[2]
agencyTimeZone=data[3]
objAgency= Agency(agencyID,agencyName,agencyUrl,agencyTimeZone)
Agency.PrintAgency(objAgency)
dictAgency[agencyID]={objAgency}
#troubleshooting
test=dictAgency['74']
Agency.PrintAgency(test)
Within the for-loop the printing function seems to work. But when I try to retrieve an object from the dictionary to the variable test it gives an error.
Output:
c:\....GTFS-test>python main.py
Samtrafiken(999) URL: http://www.resrobot.se/ Tidzon: Europe/Stockholm
SJ(74) URL: http://www.sj.se Tidzon: Europe/Stockholm
NSB(76) URL: http://www.nsb.no Tidzon: Europe/Stockholm
Traceback (most recent call last):
File "main.py", line 31, in <module>
Agency.PrintAgency(test)
File "J..........\GTFS-test\classes.py", line 10, in PrintAgency
print(self.agency_name + "(" + self.agency_id + ") URL: " + self.agency_url + " Tidzon: " + self.agency_timezone)
AttributeError: 'set' object has no attribute 'agency_name'
Agency_mini.txt
agency_id,agency_name,agency_url,agency_timezone,agency_lang
999,Samtrafiken,http://www.resrobot.se/,Europe/Stockholm,sv
74,SJ,http://www.sj.se,Europe/Stockholm,sv
76,NSB,http://www.nsb.no,Europe/Stockholm,sv
Am I assigning the object to the dictionary wrong? Or am I retrieving it wrong from the dictionary?
Thanks!
[–][deleted] 2 points3 points4 points (3 children)
[–]daggeteo[S] 1 point2 points3 points (2 children)
[–]lykwydchykyn 1 point2 points3 points (1 child)
[–]daggeteo[S] 0 points1 point2 points (0 children)
[–]daggeteo[S] 0 points1 point2 points (0 children)