简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM