Home > database >  How to create a dictionary from a file in python version 3?
How to create a dictionary from a file in python version 3?

Time:08-09

I am very new in python and I really need help.

I have a 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.

CodePudding user response:

Because the format for every file is the same, (at least I assume that). What you can do is map the person's name. 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. But some people could have more.

Edit 2: It seems that there could be more lines than implied.

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.

CodePudding user response:

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:

dict[key] = value

Now just do it with each input read in and its corresponding partner.

  • Related