How do I access this type of dictionary (a dictionary within a dictionary) in a Django template?
I would like to highly customize a DataFrame generated by Pandas in a Django view/template. I'm able to generate the dictionary that I would like to render, but accessing the elements using template tags has proven difficult.
Here is an example of the dictionary:
df_dict =
{
('Key1', 'Key2'): {
'Line 1': '',
'Line 2': '',
'Line 3': 53000.0,
'Line 4': -120000.0,
'Line 5': 45000.0
},
('Key3', 'Key2'): {
'Line 1': '',
'Line 2': 100.0,
'Line 3': '',
'Line 4': '',
'Line 5': ''
},
('Key4', 'Key2'): {
'Line 1': 1000.0,
'Line 2': '',
'Line 3': 2000.0,
'Line 4': '',
'Line 5': ''
}
}
My desired template output (without regard to css formatting) is:
Key1 Key3 Key4
Key2 Key2 Key2
Line 1 1000
Line 2 100
Line 3 53000 2000
Line 4 -120000
Line 5 45000
I've tired a simple template tag to iterate over the dictionary like this:
{% for key, value in object %}
<li>{{key}} : {{value}}</li>
{% endfor %}
but it only provides for:
Key1 : Key2
Key3 : Key2
Key4 : Key2
I can't figure out how to get into the dictionary that is the value for the above key pairs. I've also worked through countless .dot notation tags without any luck.
I've also looked other libraries that will render 'nice' html, but I would like to further customize with bootstrap
. I've also looked at wenzhixin's solution, but I would like a more flexibility.
Update for Data Structure
The information is obviously from a QuerySet, but in order to merge and pivot from multiple models, I've used Pandas. Once the dataframe is appropriately built and formatted, I've used the df_dict.to_dict()
method (where df_dict
is my dataframe) and then passed that into the context dictionary. Basically:
context = {
#stuff,
'df_dict': df_dict,
#more stuff,
}
return context
The structure I've shown is simple - it is for more likely that the column index will have three or more keys. The values size and design will be constant by design (in other words, every key group will have 5 lines of the value dictionary, or 19 lines in the value dictionary).
Final note where @ScottSkiles closed the gap - SO Question here starts out using a dictionary within a dictionary, but the answer at the very end using the template example omits the .items
method in the template and the dataset is a list. But the below answer is appropriately applied.