Merlijn Diele
Merlijn Diele

Reputation: 1

Trying to get key-value pairs from a string

I want to make a method that reads a file and returns a dictionary with the given key-value pairs in the file, but I am new to python and don't know how to do it. The string input is values followed by keys, and then a newline, like this:

6 ove
6 ver
5 rov

The keys should be the string and the values the integers. I already tried this:

with open(filename, "r", encoding="utf-8") as conn:
    text = conn.read().splitlines()
    for line in text:
        for value, key in line:
            result[key] = int(value)

But I think it reads the whole line as the value. Hope someone can help

Upvotes: 0

Views: 941

Answers (1)

Mario Ishac
Mario Ishac

Reputation: 5907

The line is a str, does not have a value and key.

To turn it into a list, you can do line.split() the string into words. It will split on any whitespace:

for value, key in line.strip().split():
    ...

The strip() removes heading and trailing spaces and linefeeds.

Upvotes: 1

Related Questions