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}}

Asked By: Tylzan

||

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}
Answered By: Unmitigated

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

Answered By: Naveed Patel

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.

Answered By: Rohlex32

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

Answered By: Alessio Michelassi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.