我在尝试使用pickle保存字典时一直收到此错误,有人可以帮忙吗?
Traceback (most recent call last):
File "/home/euan/Documents/Python/Task 1.04.py", line 31, in <module>
change_rate()
File "/home/euan/Documents/Python/Task 1.04.py", line 9, in change_rate
rates.update(new_rate[old_rate])
TypeError: 'float' object is not subscriptable
我的代码是:
import pickle
rates = {"Dollar": 0.67, "Pound": 0.47, "Euro": 0.00, "Yen": 0.00}
rates = pickle.load(open("rates.dat" , "rb"))
def change_rate():
i = input("Which exchange rate would you like to change? Dollar, Pound, Euro,Yen:")
old_rate = rates[i]
new_rate = float(input("Please input the new exchange rate: "))
rates.update(new_rate[old_rate])
pickle.dump(rates,open("rates.dat", "wb"))
rep = input("Would you like to change another rate y/n? ")
if rep == "y":
change_rate()
else:
pass
答案 0 :(得分:0)
您将new_rate
设为float
值,然后尝试将其视为数组(new_rate[old_rate]
)。订阅(从数组中选择一个项目)在应用于浮点数时没有任何意义;这正是错误信息试图告诉你的内容。
答案 1 :(得分:0)
您不需要update
来修改字典。只需更改单个条目。
rates[i] = new_rate
new_rate
和old_rate
都是浮点数,在您尝试执行浮点数时,在浮点数上做下标是没有意义的:new_rate[old_rate]
。
答案 2 :(得分:0)
替换这个:
rates.update(new_rate[old_rate])
为:
rates.update([(i,new_rate)])
如果您想使用dict.update
只需你可以做到:
rates[i] = new_rate