Skip to main content
 首页 » 编程设计

python之在 python 中从文件中检索字典键时出错

2025年05月04日13exmyth

SO 上有类似的问题/答案,但这是指一个特定的错误,我已经引用了相关的 SO 主题来解决这个问题,但没有运气。

我的代码试图从文本文件中检索行并将它们读入字典。它有效,但正如您在下面看到的那样,并不完全。

文件

"['a', 5]" 
"['b', 2]" 
"['c', 3]" 
"['d', 0]" 

代码

def readfiletodict(): 
 
   with open("testfile.txt","r",newline="") as f: 
     mydict={} #create a dictionary called mydict 
     for line in f: 
        (key,val) = line.split(",") 
        mydict[key]=val 
     print(mydict) #test 
     for keys in mydict: 
       print(keys) #test to see if the keys are being retrieved correctly 
 
 
readfiletodict()      

期望的输出:

我希望字典 包含键:a、b、c、d 和相应的值,如文件中所示,没有不需要的字符。同样,我需要将值作为整数正确存储在字典中(以便以后可以使用它们)

有关快速复制,请参阅:https://repl.it/KgQe/0对于整个代码和问题

当前(错误)输出:

Python 3.6.1 (default, Dec 2015, 13:05:11) 
[GCC 4.8.2] on linux 
 
{'"[\'a\'': ' 5]"\r\n', '"[\'b\'': ' 2]"\r\n', '"[\'c\'': ' 3]"\r\n', '"[\'d\'': ' 0]"\r\n'} 
"['a' 
"['b' 
"['c' 
"['d' 

我在当前代码中使用的 Stackoverflow 答案来自:Python - file to dictionary?但它对我来说不太管用......

请您参考如下方法:

您的代码略有修改 - 关键是去除所有我们不关心的字符 ( [Python]: str.rstrip([chars]) ):

def readfiletodict(): 
    with open("testfile.txt", "r") as f: 
        mydict = {} #create a dictionary called mydict 
        for line in f: 
            key, val = line.strip("\"\n[]").split(",") 
            mydict[key.strip("'")] = val.strip() 
    print(mydict) #test 
    for key in mydict: 
        print(key) #test to see if the keys are being retrieved correctly 
 
 
readfiletodict() 

输出:

(py35x64_test) c:\Work\Dev\StackOverflow\q46041167>python a.py 
{'d': '0', 'c': '3', 'a': '5', 'b': '2'} 
d 
c 
a 
b