0

I want to create a nested dictionary in such a form:

{
    catagory_name: {1: abc, 2: efg},
    category_name: {1: pqr, 2: stu},
    category_name: {1: vwx, 2: ijk, 3: lmn}
}

Where I will fetch category1_name, category2_name and category3_name from a table1 and then I will for loop it to execute new query and fetch values abc, efg, pqr, stu and vwx, ijk, lmn from next table based on Ids fetched from table1.

Something like this:

categories = cat.getAllCatagories()

for value in categories:
    categoriesData = {}
    subCategories = cat.getSubCategoriesByCategoryId(value.id)
    for val in subCategories:
        categoriesData[values.name] = val.name

context = {'categoriesData': categoriesData}

return render(request, 'demo/test/industries_catagories.html', context)

Now I want to access this categoriesData dictionary in my template of Django framework and list it form of tree structure.

Any ideas will be very much appreciated.

Sources I referred SO question are very complicated.

mariodev
  • 13,119
  • 3
  • 45
  • 56
Alwaysalearner
  • 3,137
  • 9
  • 45
  • 85
  • Pasting the dictionary you provide as an example, in a python shell errors are raised. If I try to correct them, the result is something different from your example. – raratiru Sep 21 '17 at 15:19
  • @raratiru Can you please paste that result here? – Alwaysalearner Sep 21 '17 at 15:26
  • a dictionary(or dict for short) is a key value pair. Meaning that each key have a value. Therefor the keys must be unique. You have three keys with the same name: catagory_name. Consider having your key like so: catagory_name_1, catagory_name_2, catagory_name_3. – Daniel Heidemann Sep 21 '17 at 15:42
  • @DanielHeidemann explained well, but there is also a typo which makes the situation worse: `{'catagory_name': {1: 'abc', 2: 'efg'}, 'category_name': {1: 'vwx', 2: 'ijk', 3: 'lmn'}}`. The issue is that if you know exactly what you are looking, complex structures might become self-explanatory. – raratiru Sep 21 '17 at 17:21

0 Answers0