簡體   English   中英

值錯誤:字典更新序列元素 #6 的長度為 1; 2 是必需的

[英]ValueError: dictionary update sequence element #6 has length 1; 2 is required

我有一些 Python 代碼旨在獲取一些數據並從該數據重新創建一個字符串,但我收到一個錯誤。

def remove_cruft(s):
     return s[1:-2]

import re

filetouse = input("What file would you like to use?\n>>>")
filetouse = filetouse + ".txt"
f = open(filetouse,"r")
lines = f.readlines()
indexlist = lines[2]
indexdict = lines[1]

indexdict = indexdict.split()
indexdict.remove("['")
indexdict.remove("']") 
for item in indexdict:
    if "'," in indexdict:
        indexdict.remove("',")
    if "'" in indexdict:
        indexdict.remove("'")
    if '",' in indexdict:
        indexdict.remove('",')
    if '"' in indexdict:
        indexdict.remove('"')

indexdict = str(indexdict)
indexdict = indexdict[1:-1]
indexdict.replace(" ", "")

dict(x.split('=') for x in indexdict.split(','))

print(indexlist)
print(indexdict)
newindexlist = remove_cruft(indexlist)
newindexlist = re.findall(r"[\w']+|[.,!?;]", newindexlist)
del newindexlist[1::2]
print(newindexlist)

posindexdict = 0
finaloutput = []

print(finaloutput)

錯誤:

Traceback (most recent call last):
  File "\\IOTA\ControlledAssessment\assess87\My Documents\Python\Task 3\Decompression v1.3.py", line 31, in <module>
    dict(x.split('=') for x in indexdict.split(','))
ValueError: dictionary update sequence element #6 has length 1; 2 is required

dict的參數選項之一是可迭代對象的可迭代對象,其中每個對象正好有兩個對象:

>>> dict((('a', 1), ('b', 1)))
{'a': 1, 'b': 1}

您的代碼試圖傳入一個可迭代對象,其中一個子可迭代對象只有一個對象:

>>> dict((('a', 1), ('b')))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #1 has length 1; 2 is required

根據輸出,數據中的第 7 個元素似乎不是您期望的格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM