我无法调用我创建的用于打开CSV文件的函数。我收到一个错误:
AttributeError:“函数”对象没有属性“键”。
在我的for
循环中,不会加载我从该函数创建的load_dict
。任何帮助表示赞赏!请放轻松,我是初学者。
import csv
invest_dict = 'DOW_Stock_short.csv'
def load_dict():
with open(invest_dict , 'r') as invest_obj:
invest_reader = csv.reader(invest_obj)
result = {}
for row in invest_reader:
if invest_reader.line_num !=1:
key = row[0]
result[key] = float(row[1])
return(result)
print("The purpose of this project is to provide Stock Analysis by reading \n the data from a csv file and performing analysis on this data.")
def Greeting():
print(".........Welcome.............")
def Conversions(investment_amount):
investment_amount = float(investment_amount)
Euro = float(round(investment_amount / 1.113195,2) )
Pound = float(round(investment_amount / 1.262304,2) )
Rupee = float(round(investment_amount / 0.014316,2) )
print("The amount you invest in euro is: {:.2f}" .format(Euro) )
print("The amount you invest in pounds is: {:.2f}" .format(Pound) )
print("The amount you invested in Rupees is: {:.2f}" .format(Rupee) )
def minimum_stock():
key_min = min(load_dict.keys(), key = (lambda k: load_dict[k]))
print("The lowest stock you can buy is: ",load_dict[key_min])
def maximum_stock():
key_max = max(load_dict.key(), key = (lambda k: load_dict[k]))
print("The highest stock you may purchase is: ",load_dict[key_max])
def invest_range(investment_amount):
new_list = []
new_list = [i for i in load_dict if i >=50 and i <=600]
return(sorted(new_list))
answer = 'yes'
while answer:
print(Greeting())
try:
investment_amount = float(input("Please enter the amount you want to invest:$ "))
print("Thank you for investing:$ {:,.2f}".format(investment_amount))
except:
print("Please enter a valid amount...")
continue
print(Conversions(investment_amount))
for i in load_dict():
i = investment_amount
if i <25:
print("Not enough funds to purchase stock")
break
elif i>25 and i <250:
print(minimum_stock())
break
elif i >= 250 and i <= 1000:
print(maximum_stock())
break
print("This is the range of stocks you may purchase: ", invest_range(investment_amount))
answer = input("Would you like to complete another conversion? yes/no " )
if answer == 'no':
print("Thank you for investing.")
break
我希望输出根据用户输入内容显示字典的内容。错误消息:
AttributeError:“函数”对象没有属性“键”
答案 0 :(得分:0)
简而言之:您没有将.keys()
应用于函数的结果,而是将其应用于函数本身,这就是错误的意思。尝试改为调用该函数:
# Wrong:
# load_dict.keys()
load_dict().keys()
这可能(可能)解决了您的问题,但是从我在其余代码中所看到的,您多次使用该函数,就像应该使用它的结果一样。因此,最好在使用结果之前先对其进行缓存:
load_dict = load_dict()
load_dict.keys()