为已创建的字典中的空键添加值



所以我基本上需要添加一个值从一个txt文件到output_dic中的键,并以以下格式为这两年

这个想法是从按行和列组织的TXT中获取数据,并处理它以获得以下输出

中组织的数据

2020                 2021        
Max Volume (Date)                       'value added'       'value2 added'
Min Volume (Date)
import matplotlib.pyplot as plt
import time     
import pandas as pd

def main(): 

again = "y"     

while again.lower() == 'y' or again.lower() == "yes":



output_dic = {'Max Volume (Date)': ["", "", ""],
'Min Value (Date)' : ["" , "", ""],
'Lowest Open (Date)' : ["", "", ""] ,
'Highest Close (Date)' : ["", "", ""],
'Highest Monthly Average (Months)' : ["", "" , ""],
'Lowest Monthly Average (Months)' : ["", "", ""],
'Annual Average (Months)' : ["", "", ""]}

print("n{:^91}n".format("Apple Stock Analysis 2020 and 2021"))
print("{:^31} {:^20} {:^20}" .format(" ", "2020", "2021" , "total"))
print("-" * 91)


for k, v in output_dic.items():
y2020, y2021, y2022 = v 
print( "{:<31} {:^20} {:^20} {:^20}" .format(k , y2020, y2021, y2022))
break


output_dic.update({'Max Volume (Date)' :  })

print(output_dic)

您可以通过简单地将值分配给键来向字典添加值,例如,如果键已经存在,则新值将替换旧值,例如:

output_dic['Max Volume (Date)'] = [0, 1, 2]

为了完整,我将编写一个示例代码片段,说明如何用字典中已赋值的值替换从.txt文件中读取的值:

output_dic = {'Max Volume (Date)': ["", "", ""],
'Min Value (Date)' : ["" , "", ""],
'Lowest Open (Date)' : ["", "", ""] ,
'Highest Close (Date)' : ["", "", ""],
'Highest Monthly Average (Months)' : ["", "" , ""],
'Lowest Monthly Average (Months)' : ["", "", ""],
'Annual Average (Months)' : ["", "", ""]}
keys_list = ['Max Volume (Date)', 'Min Value (Date)', 'Lowest Open (Date)', 'Highest Close (Date)', 'Highest Monthly Average (Months)', 'Lowest Monthly Average (Months)', 'Annual Average (Months)']
input_file_address = 'E://file_name.txt'
with open(input_file_address, 'r') as input_file:
index = 0
for line in input_file:
line_stripped = line.strip() # .txt files' lines usually end with n and they could also have whitespace at the beginning by mistake, this line removes these issues

if line_stripped == '': # if the line is empty, move to the next line
continue

line_splitted = line_stripped.split(' ') # If the values are separated by whitespace, this line would convert a string of for example 'a b c' to a list of ['a', 'b', 'c'] 

key = keys_list[index]
output_dic[key] = line_splitted
index += 1
print(output_dic)

假设。txt文件格式如下:

value_1、value_2 value_3 ..................................................

,其中每行对应一个不同的参数,例如"MinValue"等等。

最后我想提出一个建议:我认为。txt不是适合这些类型操作的文件格式,我个人更喜欢。csv,它更容易解析,因为格式是通用的,不像。txt文件,任何人都可以用任何格式写任何东西。

相关内容

  • 没有找到相关文章