python-3.x - 如何使用 .csv 文件创建字典并将其用作函数?
问题描述
我有一个导入的 .csv 文件,基本上我需要的是从 .csv 文件创建一个字典并将其与我现有的代码一起使用。我希望能够将其用作函数,并能够在需要时调用新字典及其值。这是我到目前为止所拥有的:
csv文件内容:
Price Volume 52WeekHigh 52WeekLow DividendYield PE_Ratio
150.75 41.03 233.47 142 1.97% 12.34
98.65 3.23 114.55 87.54 1.60% 23.03
340.53 4.74 394.28 292.47 2.51% 19.03
129.77 4.2 173.24 112.06 2.68% 20.15
111.77 5.67 133.88 100.22 4.04% 14.8
111.42 8.73 120.2 97.68 1.61% 13.05
175.37 2.69 275.31 151.7 1.83% 12.31
177.89 4.72 215.43 158.09 2.37% 18.85
119.83 4.76 171.13 105.94 5.35% 18.65
47.74 22.75 57.5995 14.44%
代码片段
import csv
#import csv file.
invest_dict = 'DOW_Stock_short.csv'
with open(invest_dict , 'r') as invest_obj:
invest_dict = 'DOW_Stock_short.csv'
invest_reader = csv.reader(invest_obj)
result = {}
for row in invest_reader:
if invest_reader.line_num !=1:
key = row[0]
result[key] = row[1]
print(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(result, key = (lambda k: result[k]))
print("The lowest stock you can buy is: ",result[key_min])
def maximum_stock():
key_max = max(result, key = (lambda k: result[k]))
print("The highest stock you may purchase is: ",result[key_max])
def invest_range(investment_amount):
new_list = []
new_list = [i for i in result 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 result:
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
解决方案
推荐阅读
- javascript - Nuxt:身份验证 + Axios 设置
- python - Python 3 从现有列表中随机选择
- c++ - 为什么我不能用 std::tuple 保证复制省略?
- windows - Docker暴露端口不可达
- javascript - Gulp 创建一个新的 dist 文件夹
- css - 在反应中渲染wordpress模板时的样式问题
- mysql - 如何使用存储在另一个数据库中的权限过滤数据库结果
- javascript - 以迭代方式更改 JSON 对象的每个关键元素
- c# - 为什么 MathJax 不适用于转发器页面更改?
- reactjs - useLayoutEffect、useRef 超过了最大更新深度