简体   繁体   English

KeyError字典转换Python

[英]KeyError Dictionary Conversion Python

I would like to create a program that converts money from one type of currency to another. 我想创建一个程序,将钱从一种货币转换为另一种货币。 So far this is my code: 到目前为止,这是我的代码:

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)

It should return the converted amount along with it's currency code (othercode) but instead it returns a KeyError. 它应返回转换后的金额以及其货币代码(其他代码),但应返回KeyError。 If I type 如果我输入

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

it should return GBP somenumber. 它应该返回GBP somenumber。 This is the error. 这是错误。 Thank you! 谢谢!

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'

Are you sure your file contains 'USD' key? 您确定文件中包含“ USD”密钥吗?

Here is a slightly modified and simplified code (so I didn't have to create an exchange file): 这是经过稍微修改和简化的代码(因此,我不必创建交换文件):

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)

This prints out GBP494.0 . 打印出GBP494.0

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

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