简体   繁体   中英

Python- how to convert lines in a .txt file to dictionary elements?

Say I have a file "stuff.txt" that contains the following on separate lines: q:5 r:2 s:7

I want to read each of these lines from the file, and convert them to dictionary elements, the letters being the keys and the numbers the values. So I would like to get y ={"q":5, "r":2, "s":7}

I've tried the following, but it just prints an empty dictionary "{}"

y = {} 
infile = open("stuff.txt", "r") 
z = infile.read() 
for line in z: 
    key, value = line.strip().split(':') 
    y[key].append(value) 
print(y) 
infile.close()

try this:

d = {}
with open('text.txt') as f:
    for line in f:
        key, value = line.strip().split(':')
        d[key] = int(value)

You are appending to d[key] as if it was a list. What you want is to just straight-up assign it like the above.

Also, using with to open the file is good practice, as it auto closes the file after the code in the 'with block' is executed.

There are some possible improvements to be made. The first is using context manager for file handling - that is with open(...) - in case of exception, this will handle all the needed tasks for you.

Second, you have a small mistake in your dictionary assignment: the values are assigned using = operator, such as dict[key] = value.

y = {} 
with open("stuff.txt", "r") as infile: 
    for line in infile: 
        key, value = line.strip().split(':') 
        y[key] = (value) 

print(y) 

Python3:

with open('input.txt', 'r', encoding = "utf-8") as f:
    for line in f.readlines():
        s=[] #converting strings to list
        for i in line.split(" "):
            s.append(i)
        d=dict(x.strip().split(":") for x in s) #dictionary comprehension: converting list to dictionary
        e={a: int(x) for a, x in d.items()} #dictionary comprehension: converting the dictionary values from string format to integer format
        print(e)

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