繁体   English   中英

KeyError字典转换Python

[英]KeyError Dictionary Conversion Python

我想创建一个程序,将钱从一种货币转换为另一种货币。 到目前为止,这是我的代码:

def read_exchange_rates(exchange_file_name):
    #reads file with exchange rates formatted like USD,1. Each line is a 3 letter currency code and a float to convert it to USD. 
    f=open(exchange_file_name,"r")
    answer={}
    for line in f:
        k, v = line.split(",")
        answer[k] = float(v)
    return answer
    f.close()
    pass
class Money:

    exchange_rates = read_exchange_rates(rate_file)
    #calls previously defined function to read file with exchange rates
    def __init__ (self, monamount, code):
        self.monamount=monamount
        self.code=code
    def to(self, othercode):
        i = self.monamount/self.exchange_rates[self.code]
        j = i*self.exchange_rates[self.othercode]
        return othercode+str(j)

它应返回转换后的金额以及其货币代码(其他代码),但应返回KeyError。 如果我输入

a=Money(650,'USD')
b=a.to('GBP')

它应该返回GBP somenumber。 这是错误。 谢谢!

Traceback (most recent call last):
  File "<pyshell#126>", line 1, in <module>
    b=a.to('GBP')
  File "<pyshell#124>", line 9, in to
    i = self.monamount/self.exchange_rates[self.code]
KeyError: 'USD'

您确定文件中包含“ USD”密钥吗?

这是经过稍微修改和简化的代码(因此,我不必创建交换文件):

def read_exchange_rates():
    answer={}
    answer['USD'] = 1
    answer['GBP'] = 0.76
    return answer

class Money:
    exchange_rates = read_exchange_rates()
    def __init__ (self, monamount, code):
        self.monamount = monamount
        self.code = code

    def to(self, othercode):
        i = self.monamount/self.exchange_rates[self.code]
        j = i*self.exchange_rates[othercode]
        return othercode + str(j)

a = Money(650,'USD')
b = a.to('GBP')
print(b)

打印出GBP494.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM