Artem Ilin
Artem Ilin

Reputation: 375

Django: how to process flat queryset to nested dictionary?

I have a table with data looking like this:

|Country|State|City |Street|
|-------|-----|-----|------|
|  USA  | AZ  |city1| str1 |
|  USA  | AZ  |city1| str2 |
|  USA  | AZ  |city2| str1 |
|  USA  | AZ  |city2| str3 |
|  USA  | MN  |city3| str4 |
|  MEX  | CH  |city4| str5 |
|  MEX  | CH  |city4| str6 |

What is a proper way to convert this into nested dictionary? I expect the result looking like this:

nested_dict = {
    'USA':{
        'AZ':{
            'city1':['str1','str2'],
            'city2':['str1','str3'], 
        },
        'MN':{
            'city3':['str3','str4'], 
        },
    },
    'MEX':{
        'CH':{
            'city4':['str5','str6'],
        },
    },
}

Upvotes: 2

Views: 1182

Answers (1)

user2390182
user2390182

Reputation: 73498

You can use a nested defaultdict:

from collections import defaultdict as dd

nested_dict = dd(lambda: dd(lambda: dd(list)))
for m in model.objects.all():
    nested_dict[m.Country][m.State][m.City].append(m.Street)

Upvotes: 2

Related Questions