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



我是python的新手,我真的需要帮助。

我有一个功能:

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

我有一个文件,里面有这样的数据:

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

使用它,我必须创建一个看起来像这样的字典:

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

我开始做这个:

input_file=打开('data.txt'(get_data(input_file(,这是我得到的答案:("Tom Brady","45678","余额:456","年利率:0.32"(

这是我的代码:

while file.readline != '':
name = file.readline().strip()
ignore = file.readline().strip()
num = file.readline().strip()
balance = file.readline().strip()
rate = file.readline().strip()
return (name, num, balance, rate)

但问题是我必须阅读整个文件。看起来我可以读取整个文件,我必须分别分配每个变量,但我不能这样做,因为它们不总是8个块。我还得想办法跳过余额和利率,但我不知道怎么做。

因为每个文件的格式都是相同的(至少我认为是这样(。你能做的就是把这个人的名字映射出来。要从文件中读取输入,请首先使用打开文件

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

然后从文件中一次读取一行do:

f.readline()

现在只是将它们分配给变量。

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()

现在下一步是将它添加到字典中。

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.

编辑:请确认输入有多少行,如果只有这两个帐户有8行,那就好了。但有些人可以拥有更多。

编辑2:似乎行数可能比隐含的要多。

如果只是简单地添加一个while循环,使下一个读取行不是None,只要不是,就有更多的行要读取,那么只需读取所需的输入并将其添加到字典中。

正如RollyPanda上面所说,只需使用循环迭代并读取输入,除了每次使用语法将它们添加到字典中:

dict[key] = value

现在,只需对读入的每个输入及其相应的伙伴进行操作。

最新更新