繁体   English   中英

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

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

假设我有一个文件“stuff.txt”,其中包含以下内容:q:5 r:2 s:7

我想从文件中读取每一行,并将它们转换为字典元素,字母是键,数字是值。 所以我想得到 y ={"q":5, "r":2, "s":7}

我尝试了以下方法,但它只打印一个空字典“{}”

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()

试试这个:

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

您正在附加d[key] ,就像它是一个列表一样。 你想要的只是像上面那样直接分配它。

此外,使用with打开文件是一种很好的做法,因为它会在执行'with block'中的代码后自动关闭文件。

有一些可能的改进。 第一种是使用上下文管理器进行文件处理 - 即with open(...) - 如果发生异常,这将为您处理所有需要的任务。

其次,在字典赋值中有一个小错误:使用=运算符赋值,例如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)

暂无
暂无

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

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