i am using the django shell to try to create such a dictionary:
{'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 = 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?
CodePudding user response:
You should only construct a new list if the category is not yet defined in the mydict[section
, so:
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
:
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]. Use for examplemydict
.