这种情况一般出现于使用dict()函数将字典类型或其它数据类型转为字典类型时。
dict函数正确的转换
更详细的使用方法,请自行查阅,下面的代码是dict()函数的参数是python数据类型的情况,如下:
d1 = dict([('one', 1), ('two', 2), ('three', 3)]) # 参数是列表
print(d1, type(d1))
numbers1 = dict({'x': 4, 'y': 5}) # 参数是一个字典
print(numbers1, type(numbers1))
运行结果:
{'one': 1, 'two': 2, 'three': 3} <class 'dict'>
{'x': 4, 'y': 5} <class 'dict'>
我的错误原因
请看我的代码,我以为使用dict函数可以将列表直接转为字典,两边的中括号自动去除,可是报错 了。
lst = [{'name': '1', 'id': 10001, 'python': 1.0, 'c': 2.0, 'cpp': 3.0}]
d = {}
d = dict(lst) # ValueError: dictionary update sequence element #0 has length 5; 2 is required
print(d, type(d))
修改后的代码:
lst = [{'name': '1', 'id': 10001, 'python': 1.0, 'c': 2.0, 'cpp': 3.0}]
d = {}
for item in lst:
d = dict(item)
print(d, type(d))
这下ok了,运行结果:
{'name': '1', 'id': 10001, 'python': 1.0, 'c': 2.0, 'cpp': 3.0} <class 'dict'>