我需要货币汇率更新脚本,但存在以下问题
如果调用该接口,则会收到以下响应:
"base": "USD",
"rates": {
"AED": 3.672782,
"AFN": 57.680075,
"ALL": 130.5485,
"AMD": 477.866,
"ANG": 1.78952,
"EUR": 0.927815,
"AOA": 107.13525,
...
问题是,我需要将欧元转换为货币汇率。这意味着我的基本汇率是美元,但我需要欧元。
是否有任何选项可以从此JSON计算基本汇率为USD的货币汇率到基本汇率为EUR的货币汇率。
最佳答案
鉴于:
rates = {
'AED': 3.672782,
'AFN': 57.680075,
'ALL': 130.5485,
'AMD': 477.866,
'ANG': 1.78952,
'EUR': 0.927815,
'AOA': 107.1352,
'USD': 1.0 } # base in rates needed to convert to/from base
rates
可用于支持任意转换:def convert_currency(rates, value, src_curr, dest_curr):
return value / rates[src_curr] * rates[dest_curr]
正在使用:
>>> convert_currency(3.50, 'ANG', 'EUR')
1.81465001788189
>>> convert_currency(1.00, 'USD', 'EUR')
0.927815
要将
rates
更改为新的基准,请执行以下操作:def rates_with_new_base(rates, old_base, new_base):
new_rates = {curr: rate/rates[new_base] for curr, rate in rates.items()}
# only needed if old base was not in rates table
new_rates[old_base] = 1.0 / rates[new_base]
return new_rates
正在使用:
>>> rates_with_new_base(rates, 'USD', 'EUR')
{'AED': 3.9585283704186724,
'AFN': 62.16764656747305,
'ALL': 140.70531302037583,
'AMD': 515.0444862391748,
'ANG': 1.9287465712453453,
'AOA': 115.47043322214019,
'EUR': 1.0,
'USD': 1.0778010702564629}