【问题标题】:ValueError: dictionary update sequence element #0 has length 1; 2 is required while reading from fileValueError:字典更新序列元素 #0 的长度为 1;从文件读取时需要 2
【发布时间】:2015-08-30 20:34:30
【问题描述】:

我正在尝试从文件中读取字典,然后将字符串转换为字典。我有这个,

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}

我希望能够返回一个字典,以便我可以轻松访问敌方角色的 hp 和其他值。

【问题讨论】:

  • 你最好使用 json 或 pickle 来存储你的字典

标签: python file dictionary


【解决方案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,我假设您想匹配它。

【讨论】:

    【解决方案2】:

    对于遇到此线程的其他人:在 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 
    

    【讨论】:

      猜你喜欢
      • 2015-02-22
      • 2018-03-20
      • 2021-04-01
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      • 2020-12-14
      • 2018-11-07
      相关资源
      最近更新 更多