ValueError:字典更新序列元素#6的长度为1; 2是必需的

时间:2016-05-04 08:40:51

标签: python

我有一些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

1 个答案:

答案 0 :(得分:0)

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个元素似乎不是您期望的格式。