我正在尝试从文件中读取字典,然后将字符串放入字典中。我有这个,
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()
不解析 Python 字典文字语法;它不会接受字符串并解释其内容。它只能接受另一个字典或一系列键值对,您的行与这些条件不匹配。
您需要使用ast.literal_eval()
function而是在这里:
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 - 值错误: dictionary update sequence element #0 has length 1; 2 is required while reading from file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30843620/