1

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

Tylzan
  • 101
  • 4
  • Please take the [tour](https://stackoverflow.com/tour) and learn [How to Ask](https://stackoverflow.com/help/how-to-ask). In order to get help, you will need to provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – alec_djinn Mar 28 '23 at 14:03
  • Is g.category typically 'book' or 'cd'? – Rohlex32 Mar 28 '23 at 14:06
  • 1
    It should work fine like this. Is this code throwing any error? – Henrique Andrade Mar 28 '23 at 14:09

3 Answers3

3

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}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

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.

Rohlex32
  • 120
  • 9
0

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