2 回答

TA貢獻(xiàn)1765條經(jīng)驗 獲得超5個贊
您會收到此錯誤,因為您正在拆分空的換行符和文件末尾的 。拆分這些行將同時給出 和 。字典是基于的,如果您為字典提供更多或更少的要處理的項目,則會引發(fā)異常。::end::['\n']['', '', 'end', '', '']key: valueValueError
您可以在 shell 中輕松重現(xiàn)此異常:
>>> 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
您可以通過剝離空空格或換行符并將拆分的項目解壓縮到由塊保護(hù)的元組中來避免這種情況。當(dāng)我們遇到無效行時,將觸發(fā)此異常處理程序。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'}
請注意我如何打印異常以查看發(fā)生了什么。代碼無法解壓縮鍵和值對,因為它有超過 2 個項目要從中解壓縮。代碼仍然創(chuàng)建了字典,但我記錄了異常以查看實際發(fā)生了什么。這很容易看到你的代碼出錯的地方。line.split(":")

TA貢獻(xiàn)1946條經(jīng)驗 獲得超4個贊
s.split(':')將為您提供一個包含兩個或多個元素的數(shù)組。例如["clientSelect ", " Long Company Name Inc."]
您必須從此數(shù)組中選擇元素來構(gòu)造字典,例如
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.'}
添加回答
舉報