简体   繁体   English

如何从 python 版本 3 中的文件创建字典?

[英]How to create a dictionary from a file in python version 3?

I am very new in python and I really need help.我是 python 的新手,我真的需要帮助。

I have a function:我有一个 function:

def get_data(file: TextIO) -> dict[tuple[str, int], list[list[float]]]

I have a file with datas like this:我有一个包含如下数据的文件:

Tom Brady
45678
Chequing Account
Balance: 456
Interest rate per annum: 0.32
Savings Account 1
Balance: 4050
Interest rate per annum: 5.6

using that I have to create a dictionary that would look like this:使用它我必须创建一个看起来像这样的字典:

{("Tom Brady",45678 ): [[456.0, 4050.0], [0.32, 5.6]]}.

I tried to find the answer on stack overflow but most of them their data are not structured.我试图找到堆栈溢出的答案,但他们中的大多数数据都不是结构化的。

Because the format for every file is the same, (at least I assume that).因为每个文件的格式都是相同的,(至少我假设是这样)。 What you can do is map the person's name.你可以做的是 map 这个人的名字。 To read input from a file first open the file with:要从文件中读取输入,首先使用以下命令打开文件:

f = open("demofile.txt", "r")

Then to read a line one at a time from the file do:然后从文件中一次读取一行:

f.readline()

Now just to assign them to variables.现在只是将它们分配给变量。

name = f.readline() # This is for the name
num = f.readline() # Next number
bal1 = f.readline() # For the first balance of the file
ignore = f.readline() # This is the "Chequing" line.
interest1 = f.readline() # For the first interest
ignore = f.readline() # This is the line that says "Savings account 1"
bal2 = f.readline()
interest2 = f.readline()

Now the next step is to add it into the dictionary.现在下一步是将其添加到字典中。

bank_info = {} # Make the dict
# Now add them in
bank_info[name] = num # If you want the numbers as integers remember to turn them into ints with `int()`
# Now do the same with the rest of them.

Edit: Please confirm how many lines the input has, if it is just these two accounts with 8 lines, that would be fine.编辑:请确认输入有多少行,如果只是这两个帐户有8行,那很好。 But some people could have more.但有些人可以拥有更多。

Edit 2: It seems that there could be more lines than implied.编辑 2:似乎有比隐含的更多的行。

If so simply just add a while loop that the next read line isn't None, as long it isn't, there are more lines to read, then just read needed input and add it to the dictionary.如果是这样,只需添加一个while循环,下一个读取的行不是None,只要不是,就有更多行要读取,然后只需读取所需的输入并将其添加到字典中。

As RollyPanda said above, just iterate through with a loop and read in the inputs, except add them into the dictionary every time with syntax:正如 RollyPanda 上面所说,只需使用循环遍历并读取输入,除了每次使用语法将它们添加到字典中:

dict[key] = value

Now just do it with each input read in and its corresponding partner.现在只需对读入的每个输入及其对应的伙伴执行此操作即可。

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

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