Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

I'm trying to read a dictionary off a file and then make the string into a dictionary. I have this,

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

and the line in the txt file is,

slime {'hp':5,'speed':1}

I'd like to be able to return a dict so that I can easily access the hp and other values for the enemy character.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

dict() does not parse Python dictionary literal syntax; it won't take a string and interpret its contents. It can only take another dictionary or a sequence of key-value pairs, your line doesn't match those criteria.

You'll need to use the ast.literal_eval() function instead here:

from ast import literal_eval

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

I've also adjusted the detection of self.kind a little; I'm assuming you wanted to match it if self.kind is found at the start of the line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...