【发布时间】:2015-05-05 15:02:26
【问题描述】:
我正在尝试让程序读取 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 文件的 sn-p:
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
【问题讨论】:
-
为什么你认为有问题?您有一本字典,其中键是机场代码,值是
Airport实例 - 您期待什么? -
那是从我试图将字典放在它自己的类中时开始的。在那里改变了它并且它起作用了。谢谢
标签: python class csv dictionary