1

I've got a dictionary like {'a':{'c':2, 'd':4 }, 'b': {'c':'value', 'd': 3}}

How can I display this into a table in view?

user469652
  • 48,855
  • 59
  • 128
  • 165

3 Answers3

3

Question is answered here:

In summary you access the code as you would for a python dictionary

data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }

You can use the dict.items() method to get the dictionary elements:

<table>
<tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
</tr>

{% for key, values in data.items %}
<tr>
    <td>{{key}}</td>
    {% for v in values[0] %}
    <td>{{v}}</td>
    {% endfor %}
</tr>
{% endfor %}
</table>
Community
  • 1
  • 1
user3404455
  • 420
  • 1
  • 3
  • 9
2

Depends on how you want to do it. In Django templates, you access keys the same way you access a method. That is, Python code like

print my_dict['a']['c']    # Outputs: 2

becomes

{{ my_dict.a.c }}    {# Outputs: 2 #}

in Django templates.

mipadi
  • 398,885
  • 90
  • 523
  • 479
1

Had a similar problem and I solved it this way

PYTHON

views.py
#I had a dictionary with the next structure
my_dict = {'a':{'k1':'v1'}, 'b':{'k2': 'v2'}, 'c':{'k3':'v3'}}
context = {'renderdict': my_dict}
return render(request, 'whatever.html', context)

HTML

{% for key, value in renderdict.items %}
    <h1>{{ key }}</h1>
    
    {% for k, v in value.items %}
      <h1>{{ k }}</h1>
      <h1 > {{ v }}</h1>
    {% endfor %}

{% endfor %}

The outputs would be 
{{ key }} = a 
{{ k }} = k1 
{{ v }} = v1  #and so forth through the loop.
kanelushi
  • 11
  • 2