0

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

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • try `for value, key in line.split(" "):` – GTBebbo May 10 '20 at 11:15
  • Does this answer your question? [How to convert a file into a dictionary?](https://stackoverflow.com/questions/4803999/how-to-convert-a-file-into-a-dictionary) with the small change of switching between `key` and `val` – Tomerikoo May 10 '20 at 11:17
  • As a side note, it is not necessary to read the whole file as a single string. remove the `text = ...` line and just do `for line in conn:` – Tomerikoo May 10 '20 at 11:21
  • Thank you Tomerikoo! That indeed answers my question! I don't know how to reference your answer as the best, but that did the trick! – Merlijn Diele May 10 '20 at 12:46

1 Answers1

1

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.

Massimo
  • 3,171
  • 3
  • 28
  • 41
Mario Ishac
  • 5,060
  • 3
  • 21
  • 52