【发布时间】:2018-02-12 22:26:00
【问题描述】:
关于 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()
期望的输出:
我希望 dictionary 包含 keys: a,b,c,d 和文件中显示的相应值,而不包含不需要的字符。同样,我需要将 values 作为 integers 正确存储在字典中(以便以后使用)
如需快速复制,请参阅: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?,但对我来说不太适用...
【问题讨论】:
-
由于某些或大多数答案在某种程度上取决于丢弃字符,因此值得考虑以下问题及其答案:stackoverflow.com/questions/3939361/…。
标签: python dictionary key