简体   繁体   English

如何使用函数打开csv并将其转换为字典?

[英]How to use a function to open a csv and convert it to a dictionary?

I am having trouble calling the function I made to open a CSV file. 我在调用打开CSV文件时使用的函数时遇到麻烦。 I am getting an error: 我收到一个错误:

AttributeError: 'function' object has no attribute 'keys'. AttributeError:“功能”对象没有属性“键”。

In my for loop it won't load the load_dict I created from the function. 在我的for循环中,它不会加载我从该函数创建的load_dict Any help is appreciated! 任何帮助表示赞赏! Please go easy, I am a beginner. 请放轻松,我是初学者。

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

I want the output to display the contents of the dictionary depending on what the user inputs. 我希望输出根据用户输入显示字典的内容。 error message: 错误信息:

AttributeError: 'function' object has no attribute 'keys' AttributeError:“函数”对象没有属性“键”

In brief: instead of appying the .keys() to the result of the function you are applying it to the function itself, and that is what the error says. 简而言之:不是将.keys()应用于函数的结果,而是将其应用于函数本身,这就是错误的意思。 Try to call the function instead: 尝试改为调用该函数:

# Wrong:
# load_dict.keys()

load_dict().keys()

This would (probably) solve your problem but from what I can see from the rest of your code, you use the function multiple times like you should use the result of it. 这可能(可能)解决了您的问题,但是从我在其余代码中所看到的,您多次使用该函数,就像应该使用它的结果一样。 So it's better to cache the result before using it: 因此,最好在使用结果之前将其缓存:

load_dict = load_dict()

load_dict.keys()

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

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