【发布时间】:2022-01-15 02:29:58
【问题描述】:
我正在使用 django shell 来尝试创建这样的字典:
{'TITLE SECTION ONE':
{'Category One': [element one],
'Category Two': [element one,
<element two},
'TITLE SECTION TWO':
{'Category One': [element one,
element two}
但是这段代码:dict[section][category] = [x] 将“二”中的“价格元素一”更改为如下结果。
dict = dict()
for x in price.objects.all():
if section not in dict:
dict[section] = {
category: [x]
}
else:
dict[section][category] = [x]
dict[section][category].append(x)
{'TITLE SECTION ONE':
{'Category One': [element two],
'Category Two': [element two,
element two},
'TITLE SECTION TWO':
{'Category One': [element two,
element two}}
如何保留所有元素?
【问题讨论】:
-
无论类别是否存在,您都创建一个新列表并在其中添加两次
x。 -
@WillemVanOnsem 我不必使用 dict[section][category] = [x] 吗?