P
P
Pavel Dyukarev2017-06-19 14:57:30
Django
Pavel Dyukarev, 2017-06-19 14:57:30

How to unpack dictionaries in a list in Django?

Hello everyone!)
Help solve the problem.
The following data structure is passed to the template context:

context = [{key:value, key:value},{key:value, key:value,},{key:value,key:value,},{key:value,key:value,}]

This is how I tried to extract key values ​​from a dictionary.
{% for menu_dict in menu_dict_list %}
        <tr>
                {% for key,value in menu_dict%}
                        <td>{{value}}</td>
                {% endfor %}
        </tr>
{% endfor %}

As a result, I wanted to get this picture:
the first dictionary ----
+ the value of the first key
+ the value of the second key
========================
the second dictionary- ----
+ value of the first key
+ value of the second key
=======================...... and so each dictionary in the list
In the template with the help of {% for in context %}
I tried to pull out the values ​​of the keys in different ways, but nothing came of it (
Either returns None.
Or iterates the key itself without values.
Help with fresh ideas.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2017-06-19
@PavelDuk

Would you show the exact code of the view, otherwise your context is equal to the list, and in the template you are already working with some kind of menu_dict_list. But suppose you have something like:

def some_view(request):
    ctx = {
        'menu_dict_list': [{'key11': 1, 'key12': 2}, {'key21': 3, 'key22': 4}, {'key31': 5, 'key32': 6}]
    }
    return render(request, 'some_template.html', ctx)

then you can get around it in the template like this:
{% for d in menu_dict_list %}
    {% for k, v in d.items %}
        {{ k }} - {{ v }}<br>
    {% endfor %}
{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question