Python ValueError:字典更新序列元素#0的长度为1;从文件读取时需要2

Python ValueError:字典更新序列元素#0的长度为1;从文件读取时需要2,python,file,dictionary,Python,File,Dictionary,我正试图从文件中读入一本词典,然后将字符串编入词典。我有这个 with open("../resources/enemyStats.txt", "r") as stats: for line in stats: if self.kind in line: line = line.replace(self.kind + " ", "") line = dict(line)

我正试图从文件中读入一本词典,然后将字符串编入词典。我有这个

with open("../resources/enemyStats.txt", "r") as stats:
        for line in stats:
            if self.kind in line:
                line  = line.replace(self.kind + " ", "")
                line = dict(line)
                return line
txt文件中的行是

slime {'hp':5,'speed':1}
我希望能够返回一个dict,以便轻松访问敌方角色的hp和其他值。

dict()
不解析Python字典文本语法;它不会接受字符串并解释其内容。它只能接受另一个字典或一系列键值对,因为您的行与这些条件不匹配

您需要在此处使用以下选项:

from ast import literal_eval

if line.startswith(self.kind):
    line = line[len(self.kind) + 1:]
    return literal_eval(line)

我还稍微调整了对
self.kind
的检测;如果在行的开头找到了self.kind,我假设您希望匹配它。

对于遇到此线程的其他人:在Python 3中,
json
包在这里实现了将字符串转换为字典的技巧:

dict('{"ID":"sdfdsfdsf"}')
# ValueError: dictionary update sequence element #0 has length 1; 2 is required

import json 
type(json.loads('{"ID":"sdfdsfdsf"}'))
# dict 

您最好使用json或pickle来存储您的dict