How to add another dictionary entry in a nested python dictionary
Question:
I would like to make a dictionary in the dictionary.
I have this code
dictionary = {}
for g in genre:
total = 0
products = Product.objects.filter(genre=g)
for product in products:
total += product.popularity
dictionary[g.category] = {g.name: total}
I would like it to look like this, for example
{‘book’: {‘Horror’:0, ‘Comedy:0}, ‘cd’: {‘Disco’: 0, ‘Rap’: 0}}
Answers:
You can use defaultdict
to store the values.
from collections import defaultdict
dictionary = defaultdict(dict)
# update it:
dictionary[g.category][g.name] = total;
# or
dictionary[g.category] |= {g.name: total}
3 cases – Do your own error checks for initializing dictionary or use setdefault or use defaultdict
Refer to this – https://stackoverflow.com/a/3483652/12948209
I think everything looks good. I bet the issue you are having is this line dictionary[g.category] = {g.name: total}
. This will writing over top of any previous entries. Add another line to append.
sub_dict = dictionary[g.category]
sub_dict[g.name] = total
This should append to the sub dictionary instead.
for g in genre:
total = 0
products = Product.objects.filter(genre=g)
for product in products:
total += product.popularity
if g.category not in dictionary:
dictionary[g.category] = {}
dictionary[g.category][g.name] = total
I would like to make a dictionary in the dictionary.
I have this code
dictionary = {}
for g in genre:
total = 0
products = Product.objects.filter(genre=g)
for product in products:
total += product.popularity
dictionary[g.category] = {g.name: total}
I would like it to look like this, for example
{‘book’: {‘Horror’:0, ‘Comedy:0}, ‘cd’: {‘Disco’: 0, ‘Rap’: 0}}
You can use defaultdict
to store the values.
from collections import defaultdict
dictionary = defaultdict(dict)
# update it:
dictionary[g.category][g.name] = total;
# or
dictionary[g.category] |= {g.name: total}
3 cases – Do your own error checks for initializing dictionary or use setdefault or use defaultdict
Refer to this – https://stackoverflow.com/a/3483652/12948209
I think everything looks good. I bet the issue you are having is this line dictionary[g.category] = {g.name: total}
. This will writing over top of any previous entries. Add another line to append.
sub_dict = dictionary[g.category]
sub_dict[g.name] = total
This should append to the sub dictionary instead.
for g in genre:
total = 0
products = Product.objects.filter(genre=g)
for product in products:
total += product.popularity
if g.category not in dictionary:
dictionary[g.category] = {}
dictionary[g.category][g.name] = total