Skip to content

Instantly share code, notes, and snippets.

@voidnologo
Last active October 3, 2021 17:54
Show Gist options
  • Save voidnologo/3d89671867e4510f2849 to your computer and use it in GitHub Desktop.
Save voidnologo/3d89671867e4510f2849 to your computer and use it in GitHub Desktop.
Displaying nested dictionaries in a Django template

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

@dtheekshanalinux
Copy link

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment