[python] how to iterate through dictionary in a dictionary in django template?

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'[email protected]',
    '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?

This question is related to python django dictionary django-templates

The answer is


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

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

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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to django-templates

Django - Did you forget to register or load this tag? How to add url parameters to Django template url tag? bootstrap 3 wrap text content within div for horizontal alignment Django, creating a custom 500/404 error page How can I get the username of the logged-in user in Django? Does Python have a toString() equivalent, and can I convert a db.Model element to String? How do I call a Django function on button click? What is the equivalent of "none" in django templates? Django - iterate number in for loop of a template Django -- Template tag in {% if %} block