CosmicCat
CosmicCat

Reputation: 622

Using methods to append text file contents into a dictionary in Python?

So I have a .txt file and I want to use methods within this class, Map, to append its contents into a aDictionary.

class Map:

    def __init__(self, dataText):
        self.dataText = dataText
        self.aDictionary = {}        

dataFile = open('data.txt', 'r')
c1 = Map(dataFile)

My data.txt file looks something like this:

hello, world

how, are

you, today

and I want aDictionary to print this output:

{how: are, you: today}

Im not very good at manipulating files as I continue to get type errors and what not. Is there an easy way of performing this task using methods within the class?

Upvotes: 1

Views: 3174

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61920

First you need to read the content of the file. Once you have the content of the file, you could create the dictionary like this (assuming content contains the content of data.txt):

content = """hello, world

how, are

you, today"""

d = {}
for line in content.splitlines():
    if line:
        key, value = map(str.strip, line.split(','))
        d[key] = value

print(d)

Output

{'you': 'today', 'how': 'are', 'hello': 'world'}

The idea is to iterate of over the lines using a for loop, then check if the line is not empty (if line), in case the line is not empty, split on comma (line.split(',')) and remove the trailing whitespaces (str.strip) for each of the values in the list using map.

Or using a dictionary comprehension:

content = """hello, world

how, are

you, today"""

it = (map(str.strip, line.split(',')) for line in content.splitlines() if line)
d = {key: value for key, value in it}
print(d)

To read the content of the file you can do the following:

content = self.dataText.read()

Further

  1. Reading entire file in Python
  2. How to read a file line-by-line into a list?

Upvotes: 2

Related Questions