2 回答

TA贡献1765条经验 获得超5个赞
您会收到此错误,因为您正在拆分空的换行符和文件末尾的 。拆分这些行将同时给出 和 。字典是基于的,如果您为字典提供更多或更少的要处理的项目,则会引发异常。::end::['\n']['', '', 'end', '', '']key: valueValueError
您可以在 shell 中轻松重现此异常:
>>> x = ["1:2", "3:4"]
>>> dict(y.split(":") for y in x)
{'1': '2', '3': '4'}
>>> x = ["1:2", "3"]
>>> dict(y.split(":") for y in x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #1 has length 1; 2 is required
>>> x = ["1:2:3", "4:5:6"]
>>> dict(y.split(":") for y in x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 3; 2 is required
您可以通过剥离空空格或换行符并将拆分的项目解压缩到由块保护的元组中来避免这种情况。当我们遇到无效行时,将触发此异常处理程序。strip()try..catch
with open("data.txt") as f:
d = {}
for line in f:
# avoid empty lines
if line.strip():
try:
# unpack key and value into tuple and strip whitespace
k, v = map(str.strip, line.split(":"))
# strip whitespace after splitting
d[k] = v
# catch error and print it out
# use pass to just ignore the error
except ValueError as ex:
print("%s occured on line: %s" % (ex, line))
pass
print(d)
输出:
too many values to unpack (expected 2) occured on line: ::end::
{'clientSelect': 'Long Company Name Inc.', 'server1Info': 'Server1', 'server1Pic': '200330135637030000.jpg', 'server2Info': 'Server2', 'server2Pic': '200330140821800000.jpg', 'modemInfo': 'Aries', 'modemPic': '200330140830497000.jpg', 'routerInfo': 'Router', 'routerPic': '200330140842144000.jpg', 'switchInfo': 'Switch1', 'switchGallery_media': '200330140859161000.jpg', 'buttonSubmit': 'Submit'}
请注意我如何打印异常以查看发生了什么。代码无法解压缩键和值对,因为它有超过 2 个项目要从中解压缩。代码仍然创建了字典,但我记录了异常以查看实际发生了什么。这很容易看到你的代码出错的地方。line.split(":")

TA贡献1946条经验 获得超4个赞
s.split(':')将为您提供一个包含两个或多个元素的数组。例如["clientSelect ", " Long Company Name Inc."]
您必须从此数组中选择元素来构造字典,例如
d = {
splited[0]: splited[1]
}
在我的蟒蛇壳中:
In [1]: s = "clientSelect : Long Company Name Inc."
In [2]: x = s.split(":")
In [3]: x
Out[3]: ['clientSelect ', ' Long Company Name Inc.']
In [4]: d = {x[0]: x[1]}
In [5]: d
Out[5]: {'clientSelect ': ' Long Company Name Inc.'}
添加回答
举报