176

My dictionary looks like this(Dictionary within a dictionary):

{'0': {
    'chosen_unit': <Unit: Kg>,
    'cost': Decimal('10.0000'),
    'unit__name_abbrev': u'G',
    'supplier__supplier': u"Steve's Meat Locker",
    'price': Decimal('5.00'),
    'supplier__address': u'No\r\naddress here',
    'chosen_unit_amount': u'2',
    'city__name': u'Joburg, Central',
    'supplier__phone_number': u'02299944444',
    'supplier__website': None,
    'supplier__price_list': u'',
    'supplier__email': u'ss.sss@ssssss.com',
    'unit__name': u'Gram',
    'name': u'Rump Bone',
}}

Now I'm just trying to display the information on my template but I'm struggling. My code for the template looks like:

{% if landing_dict.ingredients %}
  <hr>
  {% for ingredient in landing_dict.ingredients %}
    {{ ingredient }}
  {% endfor %}
  <a href="/">Print {{ landing_dict.recipe_name }}</a>
{% else %}
  Please search for an ingredient below
{% endif %}

It just shows me '0' on my template?

I also tried:

{% for ingredient in landing_dict.ingredients %}
  {{ ingredient.cost }}
{% endfor %}

This doesn't even display a result.

I thought perhaps I need to iterate one level deeper so tried this:

{% if landing_dict.ingredients %}
  <hr>
  {% for ingredient in landing_dict.ingredients %}
    {% for field in ingredient %}
      {{ field }}
    {% endfor %}
  {% endfor %}
  <a href="/">Print {{ landing_dict.recipe_name }}</a>
{% else %}
  Please search for an ingredient below
{% endif %}

But this doesn't display anything.

What am I doing wrong?

Vaibhav Vishal
  • 6,576
  • 7
  • 27
  • 48
darren
  • 18,845
  • 17
  • 60
  • 79

4 Answers4

342

Lets say your data is -

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

You can use the data.items() method to get the dictionary elements. Note, in django templates we do NOT put (). Also some users mentioned values[0] does not work, if that is the case then try values.items.

<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>

Am pretty sure you can extend this logic to your specific dict.


To iterate over dict keys in a sorted order - First we sort in python then iterate & render in django template.

return render_to_response('some_page.html', {'data': sorted(data.items())})

In template file:

{% for key, value in data %}
    <tr>
        <td> Key: {{ key }} </td> 
        <td> Value: {{ value }} </td>
    </tr>
{% endfor %}
Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
  • 3
    thanks for your answer. I have recipe_name one level up and didn't show that level of the dictionary. Thank you for your answer! I couldn't use `values[0]` instead I had to `values.items` – darren Nov 05 '11 at 08:41
  • cool! glad to share what i knew. Code was typed free hand, so some mistakes are inevitable. – Srikar Appalaraju Nov 05 '11 at 08:44
  • 1
    Thanks for mentioning `.items`. The documentation `https://docs.djangoproject.com/en/1.4/topics/templates/` gives an example that doesn't work, but no example that does work. `{% for k,v in dict %}` gives bizarre results - k is the first character of every key and v is blank, while `{% for k in dict %}` returns the full key but with no way to retrieve values (since `dict.k` treats k as a literal character). – Dave Aug 06 '15 at 00:35
  • 2
    Upvoted :-). For future readers, the tags and filters reference `https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#for` documents this, along with the forloop variables that can be helpful when formatting a list. – Dave Aug 06 '15 at 20:10
  • @Flimm dictionary is unsorted. if you want sorted order `for key in sorted(mydict.iterkeys()): print "%s: %s" % (key, mydict[key])` – Srikar Appalaraju May 25 '16 at 12:31
  • 1
    `values.items` +1 – Kevin_TA Jul 26 '17 at 16:50
  • if 'key' have ' symbol means, showing as ' How I can fix? – KarSho Jul 04 '23 at 11:18
5

This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.

This is for the following query:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

In template:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}
daaawx
  • 3,273
  • 2
  • 17
  • 16
crappy_hacker
  • 191
  • 3
  • 6
2

If you pass a variable data (dictionary type) as context to a template, then you code should be:

{% for key, value in data.items %}
    <p>{{ key }} : {{ value }}</p> 
{% endfor %}
Eugene Chabanov
  • 491
  • 5
  • 9
0

I am thankful for the above answers pointing me in the right direction. From them I made an example for myself to understand it better. I am hoping this example will help you see the double dictionary action more easily and also help when you have more complex data structures.

In the views.py:

    bigd = {}
    bigd['home'] = {'a':  [1, 2] , 'b':  [3, 4] ,'c': [5,6] }
    bigd['work'] = {'e':  [1, 2] , 'd':  [3, 4] ,'f': [5,6] }
    context['bigd']  = bigd

In the template.html:

{% for bigkey, bigvalue in bigd.items %}
    <b>{{ bigkey }}</b> <br>
    {% for key, value in bigvalue.items %}
        key:{{ key }} <br>
        ----values: {{ value.0}}, {{value.1 }}<br>
    {% endfor %}
    <br>
{% endfor %}

Notice the list in the second dictionary is accessed by the index in the list.

Result in browser is something like:

enter image description here

Anthony Petrillo
  • 365
  • 1
  • 4
  • 13