[英]python: dynamic keys in nested dictionary
我正在使用 django shell 嘗試創建這樣一個字典:
{'SECTION ONE':
{'Category One': [<Price: price element one>],
'Category Two': [<Price: price element one>,
<Price: price element two>]},
'SECTION TWO':
{'Category One': [<Price: price element one>,
<Price: price 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)
{'SECTION ONE':
{'Category One': [<Price: price element two>],
'Category Two': [<Price: price element two>,
<Price: price element two>]},
'SECTION TWO':
{'Category One': [<Price: price element two>,
<Price: price element two>]}}
你怎么能保留所有的元素?
如果類別尚未在mydict[section
中定義,您應該只構建一個新列表,因此:
mydict = {}
for x in price.objects.all():
if section not in mydict:
mydict[section] = { category: [x] }
elif category not in mydict[section]:
mydict[section][category] = [x]
else:
mydict[section][category].append(x)
另一種選擇是使用defaultdict
:
from collections import defaultdict
mydict = defaultdict(lambda: defaultdict(list))
for x in price.objects.all():
mydict[section][category].append(x)
mydict = {k: dict(v) for k, v in mydict.items()}
注意:請不要命名變量
dict
,它會覆蓋對內置dict
function [Python-doc]的引用。 使用例如mydict
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.