python - 值错误: dictionary update sequence element #0 has length 1; 2 is required while reading from file

标签 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)
                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/

相关文章:

java - 在 Java 中对文本文件进行排序

python - 将 .htm 或 .html 扩展名与 python RE 匹配

C 编程错误 : Reading from a . txt 文件

Python字典理解示例

python - 如何在 Python 中从目录中区分文件?

python - 如何根据列数据类型过滤数据框

python - 如何处理带有可调用项的 python 字典?

python - Splat 解压字典

Python-合并两个字典列表,添加重复键的值

python - 在 Python 中,f.readlines() 和 list(f) 有什么区别