[英]python: dynamic keys in nested dictionary
i am using the django shell to try to create such a 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>]}}
but this pieces of code: dict[section][category] = [x] change the "price element one" in "two" like the result below.但是这段代码: 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>]}}
how can you keep all the elements?你怎么能保留所有的元素?
You should only construct a new list if the category is not yet defined in the mydict[section
, so:如果类别尚未在
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)
another option is to work with a defaultdict
:另一种选择是使用
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()}
Note : Please do not name a variable
dict
, it overrides the reference to thedict
builtin function [Python-doc] .注意:请不要命名变量
dict
,它会覆盖对内置dict
function [Python-doc]的引用。 Use for examplemydict
.使用例如
mydict
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.