<p>正在尝试从此段文本创建dict:</p>
<pre><code>game_name: Adventure 1
game_goal: Find the magic helmet and bring it to Hans.
game_goalloc: 8
game_goalobj: helmet
game_start: 4
game_xsize: 3
game_ysize: 3
</code></pre>
<p>以“config.txt”的形式读入,不断收到类型错误:“str”对象不支持项分配</p>
<p>难道我一辈子都不明白为什么在我的代码的其他地方做同样的操作。。。地狱</p>
<pre><code>with open('config.txt') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
if "game_" in line:
game = line.split('_')[-1]
k = game.split(':')[0]
v = game.split(':')[-1]
print(k)
print(v)
game[k] = {}
game[k] = v
</code></pre>
<pre><code> game = line.split('_')[-1]
k = game.split(':')[0]
v = game.split(':')[-1]
print(k)
print(v)
game[k] = {}
game[k] = v
</code></pre>
<p>在最后两行代码中,您试图将“game”赋值为空{},然后是v。这将导致错误</p>