![](/img/trans.png)
[英]ValueError: dictionary update sequence element #0 has length 1; 2 is required Python Dictionary
[英]nosetest error: ValueError: dictionary update sequence element #0 has length 4; 2 is required
我是一个非常菜鸟,这是w / r / t python 2.7,也是我在学习Python困难方法 ( 链接到ex47 ) 上正在进行的练习 -下面的文件名为ex47_tests.py,得到的错误是与在我正在使用的目录中运行nosetests
有关。
根据nosetests
,误差是从test_map()
函数在该行west.add_paths({'east', start})
和它指出: ValueError: dictionary update sequence at element #0 has length 4; 2 is required
ValueError: dictionary update sequence at element #0 has length 4; 2 is required
但我不明白问题是什么...这是测试文件:
from nose.tools import *
from ex47.game import Room
def test_room():
gold = Room("GoldRoom",
"""This room has gold in it you can grab. There's a
door to the north.""")
assert_equal(gold.name, "GoldRoom")
assert_equal(gold.paths, {})
def test_room_paths():
center = Room("Center", "Test room in the center.")
north = Room("North", "Test room in the north.")
south = Room("South", "Test room in the south.")
center.add_paths({'north': north, 'south':south})
assert_equal(center.go('north'), north)
assert_equal(center.go('south'), south)
def test_map():
start = Room("Start", "You can go west and down a hole.")
west = Room("Trees", "There are trees here, you can go east.")
down = Room("Dungeon", "It's dark down here, you can go up.")
start.add_paths({'west': west, 'down': down})
west.add_paths({'east', start})
down.add_paths({'up': start})
assert_equal(start.go('west'), west)
assert_equal(start.go('west').go('east'), start)
assert_equal(start.go('down').go('up'), start)
作为参考,game.py文件包含具有add_paths
函数(方法?)的Room
类:
class Room(object):
def __init__(self, name, description):
self.name = name
self.description = description
self.paths = {}
def go(self, direction):
return self.paths.get(direction, None)
def add_paths(self, paths):
self.paths.update(paths)
我检查了几次,我已经成功运行的代码west.add_paths({'east', start})
的game.py文件中,但是当我运行nosetests
我不断收到同样的错误。 在代码中发生错误的那一点上,我的解释是, west
包含一个空的{}
,应该进行update
而不会出现问题,不是吗? 有人可以提供一些有关为何无法正常工作以及错误来自何处的见解吗?
非常感谢。
代码中的错误来自此调用:
west.add_paths({'east', start})
对此的更正是您要使用字典而不是集合进行更新:
west.add_paths({'east': start})
当您尝试使用集合更新字典时,以下示例可以重现此错误:
>>> d = {}
>>> d.update({'east','start'})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 5; 2 is required
为了使错误更清晰,如果转到解释器并检查其类型,请执行以下操作:
注意“东部”和“开始”之间的逗号
>>> print(type({'east', 'start'}))
<type 'set'>
注意“东部”和“开始”之间的冒号
>>> print(type({'east': 'start'}))
<type 'dict'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.