我有一个 python 字典,我想将其中的值插入数据库以快速填充我的数据库。每次我尝试此操作时都会收到以下错误:
ValueError:太多值无法解压(预计为 2 个)
这是我所拥有的:
def post(self, request):
image = "no image"
characters = {
"Auron": {'name': "Auron",
'stars': 4,
'image': image,
'series': "FF10"},
"Barret": {'name': "Barret",
'stars': 3,
'image': image,
'series': "FF7"},
"Zidane": {'name': "Zidane",
'stars': 5,
'image': image,
'series': "FF9"}
}
for key, value in characters:
number = 3
name = value.name
stars = value.stars
image = value.image
series = value.series
Characters.objects.create(id=number,name=name,stars=stars,image=image,series=series)
number += 1
return JsonResponse("Added all chars", safe=False)
此外,此代码在 ajax 调用后运行。 为什么会发生这种情况?我已经用谷歌搜索过这个,但找不到任何与我的问题类似的东西。可能是什么原因造成的?
谢谢
最佳答案
for key, value in characters.iteritems():
原因是,只有迭代字典时才能获得键。您需要显式迭代 items()
或 iteritems()
(后者通常使用较少的内存)
>>> d=dict(a=1, b=2)
>>> d
{'a': 1, 'b': 2}
>>> [x for x in d]
['a', 'b']
>>> [x for x in d.iteritems()]
[('a', 1), ('b', 2)]
>>> [x for x in d.items()]
[('a', 1), ('b', 2)]
请注意,iteritems 和 items 是元组,而字典上的直接迭代不是吗?
关于尝试从字典插入数据时,Python 的值太多而无法解压,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47933978/