简体   繁体   English

Python-如何将 .txt 文件中的行转换为字典元素?

[英]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假设我有一个文件“stuff.txt”,其中包含以下内容: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}所以我想得到 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. 您正在附加d[key] ,就像它是一个列表一样。 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. 此外,使用with打开文件是一种很好的做法,因为它会在执行'with block'中的代码后自动关闭文件。

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. 第一种是使用上下文管理器进行文件处理 - 即with open(...) - 如果发生异常,这将为您处理所有需要的任务。

Second, you have a small mistake in your dictionary assignment: the values are assigned using = operator, such as dict[key] = value. 其次,在字典赋值中有一个小错误:使用=运算符赋值,例如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: 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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