我正在尝试让程序读取CSV文件(“Airports.csv”)并将其保存到字典中,我可以在其中输入密钥,这将调用与此密钥关联的机场对象。
当我尝试打印整个列表以确保它正常工作时,它会打印密钥但打印{'GKA: <__main__.Airport object as 0x02E92570>}'
由于问题是基于使用字典对象而不是列表,你能解释我出错的地方吗?我可能已经混淆了一些它并且走错了路,因为我总是用列表而不是对象制作字典。
我附上了CSV文件和教程。
如果有人能告诉我如何正确调用字典中的对象。谢谢
import csv
class Airport:
def __init__(self, idx=-1, airportname='', cityname='', countryname='', code3='',
code4='',lat=0,long=0, altitude=0,timezone='',DST='',Tz=''):
self.idx=idx
self.airportname=airportname
self.cityname=cityname
self.countryname=countryname
self.code3=code3
self.code4=code4
self.lat=lat
self.long=long
self.lat=lat
self.altitude=altitude
self.timezone=timezone
self.DST=DST
self.Tz=Tz
def dictairportChosen(self,filename):
self.__airportDict={}
f=open(filename, encoding="utf8")
csvreader = csv.reader(f)
for idx, airportname, cityname, countryname, code3, code4, lat, long, altitude, timezone, DST, TZ, in csvreader:
airport=Airport(idx, airportname, cityname, countryname, code3, code4, lat, long, altitude, timezone, DST, TZ)
self.__airportDict[code3]=airport
print(self.__airportDict)
aAirportChosen=Airport()
aAirportChosen.dictairportChosen("airports.csv")
这是CSV文件的片段:
1,"Goroka","Goroka","Papua New Guinea","GKA","AYGA",-6.081689,145.391881,5282,10,"U","Pacific/Port_Moresby"
2,"Madang","Madang","Papua New Guinea","MAG","AYMD",-5.207083,145.7887,20,10,"U","Pacific/Port_Moresby"
3,"Mount Hagen","Mount Hagen","Papua New Guinea","HGU","AYMH",-5.826789,144.295861,5388,10,"U","Pacific/Port_Moresby"
4,"Nadzab","Nadzab","Papua New Guinea","LAE","AYNZ",-6.569828,146.726242,239,10,"U","Pacific/Port_Moresby"
5,"Port Moresby Jacksons Intl","Port Moresby","Papua New Guinea","POM","AYPY",-9.443383,147.22005,146,10,"U","Pacific/Port_Moresby"
6,"Wewak Intl","Wewak","Papua New Guinea","WWK","AYWK",-3.583828,143.669186,19,10,"U","Pacific/Port_Moresby"
7,"Narsarsuaq","Narssarssuaq","Greenland","UAK","BGBW",61.160517,-45.425978,112,-3,"E","America/Godthab"
8,"Nuuk","Godthaab","Greenland","GOH","BGGH",64.190922,-51.678064,283,-3,"E","America/Godthab"
实际教程的问题是: 2。 写 码 至 读 从 该 CSV 和 创建 一个 字典 的 飞机场 对象 更换 该 名单 在 该 字典 同 飞机场 对象。 您 应该 结束 向上 同 一个 字典 那 具有 该 飞机场 码 如 一个 键 和 一个 飞机场 宾语 如 该 抬头 值 允许 该 码 下面 至 运行:
airportLookupDict={‘DUB’, airport(….),‘LHR’, airport(….)}
myairport=airportLookupDict.get(‘DUB’)
print(myairport.name)
outputs:
DUBLIN
答案 0 :(得分:0)
答案 1 :(得分:0)
您的代码没有任何问题。它在问题中按预期工作。如果要访问列表中的各个元素,只需将实体名称添加到列表中,如下所示:
for keys, values in self.__airportDict.items():
print keys
print values.airportname