Skip to main content
 首页 » 编程设计

python之将文本文件中的所有行读取到字典python

2025年05月04日16txw1958

这里我有一个函数,当我阅读时,它只返回最后一行。我做错了什么?

def read(): 
    with open("text.txt","r") as text: 
        return dict(line.strip().split() for line in text) 

文本文件很简单,两列

asd 209 
asd 441 
asd 811 
asd 160 
asd 158 

我想将所有时间读入字典,asd 部分作为键,数字作为值。

请您参考如下方法:

字典键必须是唯一的。您在该文件中只有一个唯一 key 。

本质上,您是在为同一个键分配不同的值,并且只有最后一个值可见,因为先前的值被覆盖了:

>>> d = {} 
>>> d['asd'] = 209 
>>> d['asd'] = 441 
>>> d 
{'asd': 441} 

要存储最大值,请使用:

def read(): 
    res = {} 
    with open("text.txt","r") as text: 
        for line in text: 
            key, value = line.split() 
            if int(value) > res.get(key, -1): 
                res[key] = int(value) 
    return res