Recently came across a situtuation where I was trying to display a dictionary of dictionaries of lists in a django template. In the python code, the data structure was built like:
@property
def nested(self):
from collections import defaultdict
data = defaultdict(lambda: defaultdict(list))
for x in self.a_list_of_objects:
data['key'][x.an_attribute].append(x)
return data
This results in
{'key': {an_attribute: [item1, item2]}}
To display in django templates:
Cat(name='Kuro', color='black')
Cat(name='Nekko', color='black')
{'cat': {'black': [<Cat>'Kuro', <Cat>'Nekko']}}
{% for k, v in nested.items %}
<tr>
<td>ONE {{ k }}:{{ v }}</td>
{% for k2, v2 in v.items %}
<td>TWO {{ k2 }}:{{ v2 }}</td>
{% for k3 in v2 %}
<td>THREE {{ k3 }}</td>
{% endfor %}
{% endfor %}
</tr>
{% endfor %}
DISPLAY
ONE cat {'black': ['Kuro', 'Nekko']} | TWO black ['Kuro', 'Nekko'] | THREE Kuro | THREE Nekko |
@voidnologo Your example great I have a clue about how to get values of second loop.I meant in your exmaple
TWO black ['Kuro', 'Nekko']
how to get values of this instead of this. because I want to get that keys in dictionary.So do you have any suggestion which I highly appreciate