Edward Sikorski
Edward Sikorski

Reputation: 1

TextFile into a Dictionary

My code is working but I have a slight flaw, and I cant seem to be able to fix it. My code is:

def Identifierare():
     File = open("FulaOrd.txt","r", encoding="utf-8")
     for line in File:
                if line.strip():
                     Dict = {}
                     key, value = line.split(None, 1)
                     Dict[key] = value
                     print(Dict)

Identifierare()

My result is

{'debt': '3\n'}
{'income': '2\n'}
{'mortgage': '2\n'}
{'sale': '2\n'}

How do I take away the backslash n? In the original textfile, the words are written like this debt 3 income 2 mortgage 2 sale 2

Thanks a bunch!

Upvotes: 0

Views: 38

Answers (2)

Mark Embling
Mark Embling

Reputation: 12821

A simple answer would be to just trim the whitespace characters (including the line break) from the right of the string using the rstrip function just before you split the line.

key, value = line.rstrip().split(None, 1)

Upvotes: 0

brycem
brycem

Reputation: 593

Instead of splitting line, split line.strip() to take the carriage return and any other whitespace off the string first.

Upvotes: 2

Related Questions