0

I am trying to read in the following text file with four columns separated by commas:

1, 0.1, 0.2, 73
1, 0.11, 0.1, 101
2, 0.23, 0.01, 17
2, 0.12, 0.15, 23

where the first number represents a batch, the second and third represent an x and y coordinate respectively and the fourth is a value.

And I want to save this text file as a dictionary in python. I tried using a save_rows function to create a dictionary:

def save_rows('sample1.txt'):

    keys = ['batch', 'x', 'y', 'val']
    dicts = []
    with open(filename) as f:
        for line in f:
            line = line.strip().split(',')
            d = dict(zip(keys, line))
            return d
            dicts.append(d)

But it doesn't return or create an dictionary, what am I doing wrong?

Thanks in advance!

idlatva
  • 29
  • 7

1 Answers1

1

There were some issues in your code. Firstly, the function save_rows should take an argument like filename and then you need to pass the name of your file below in your code. For example save_rows("sample1.txt") passes sample1.txt as the argument for filename in the function. Secondly, you have used return keyword at the wrong place. I would advise you to have a look at this article to clearly understand what return does. return needs to be used at the very end to print out the list called dicts which contains all the dictionaries for the 4 rows. When you correct those two issues, your program will work fine. Below is an example of how your code should look like.

def save_rows(filename):
    keys = ['batch', 'x', 'y', 'val']
    dicts = []
    with open(filename) as f:
        for line in f:
            line = line.strip().split(',')
            d = dict(zip(keys, line))
            dicts.append(d)
    return dicts

print(save_rows("sample1.txt"))

The output that I got is as follows.

[{'batch': '1', 'x': ' 0.1', 'y': ' 0.2', 'val': ' 73'}, {'batch': '1', 'x': ' 0.11', 'y': ' 0.1', 'val': ' 101'}, {'batch': '2', 'x': ' 0.23', 'y': ' 0.01', 'val': ' 17'}, {'batch': '2', 'x': ' 0.12', 'y': ' 0.15', 'val': ' 23'}]
Pro Chess
  • 831
  • 1
  • 8
  • 23