我正在尝试使用该dict函数将列表转换为字典.
inpu = input.split(",")
dic = dict(inpu)
Run Code Online (Sandbox Code Playgroud)
上面的代码正在试图获得一个字符串,split它','事后我使用dict功能的列表转换为一个字典.
但是,我收到此错误:
ValueError:字典更新序列元素#0的长度为6; 2是必需的
有人可以帮忙吗?
zee*_*kay 20
dict期望一个可迭代的2元素容器(如元组列表).你不能只传递一个项目列表,它不知道什么是关键,什么是价值.
你正试图这样做:
>>> range(10)
<<< [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> dict(range(10))
---------------------------------------------------------------------------
TypeError: cannot convert dictionary update sequence element #0 to a sequence
Run Code Online (Sandbox Code Playgroud)
dict 期待这样的列表:
>>> zip(lowercase[:5], range(5))
<<<
[('a', 0),
('b', 1),
('c', 2),
('d', 3),
('e', 4)]
Run Code Online (Sandbox Code Playgroud)
元组中的第一个元素成为键,第二个元素成为值.
>>> dict(zip(lowercase[:5], range(5)))
<<<
{'a': 0,
'b': 1,
'c': 2,
'd': 3,
'e': 4}
Run Code Online (Sandbox Code Playgroud)