Issue
i am using the django shell to try to create such a dictionary:
{'TITLE SECTION ONE':
{'Category One': [element one],
'Category Two': [element one,
<element two},
'TITLE SECTION TWO':
{'Category One': [element one,
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)
{'TITLE SECTION ONE':
{'Category One': [element two],
'Category Two': [element two,
element two},
'TITLE SECTION TWO':
{'Category One': [element two,
element two}}
how can you keep all the elements?
Solution
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
.
Answered By - Willem Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.