Andrew
Andrew

Reputation: 12442

Loop Through List of Dict of Lists in Python and Django

I have a queryset that returns a result like below:

defaultdict(<type 'list'>,
    {
        123: 
            [
                {'field1': 123, 'field2': 'August', 'field3': 50},
                {'field1': 123, 'field2': 'September', 'field3': 25},
                {'field1': 123, 'field2': 'October', 'field3': 70}
            ],
        789: 
            [
                {'field1': 789, 'field2': 'August', 'field3': 80},
                {'field1': 789, 'field2': 'September', 'field3': 22},
                {'field1': 789, 'field2': 'October', 'field3': 456}
            ],
    })

I'm trying to loop through the list in a template, but I can only get the key to show, such that:

        {% for each in results %}
            {{ each }}<br>
        {% endfor %}

Returns:

123
789

I've tried looping through results.items, and it returns nothing. I've tried using key, value, which also returns nothing. I initially thought I'd be able to have a nested for loop, and loop through each:

        {% for each in results %}
            {% for row in each %}
                {{ row }}
            {% endfor %}
        {% endfor %}

But that returns 'int' object is not iterable

I'm not sure what I'm missing, if anyone could point me in the right direction!

Upvotes: 0

Views: 749

Answers (3)

Raj006
Raj006

Reputation: 562

I haven't seen this syntax for Python. I haven't worked with django. So, I will just use your own format, and modify just one thing. Instead of saying for row in each, you should use for row in results[each]. results is a dictionary, and each is a key. If you want the value of that dictionary for that key, you need to get it by results[each]. Now you can loop through the value if it is iterable.

    {% for each in results %}
        {% for row in results[each] %}
            {{ row }}
        {% endfor %}
    {% endfor %}

Upvotes: 2

blhsing
blhsing

Reputation: 106768

You can use the values method of a dict to obtain each sublist, which you can then iterate over in a nested loop:

{% for each in results.values %}
    {% for row in each %}
        {{ row.field1 }}
        {{ row.field2 }}
        {{ row.field3 }}
    {% endfor %}
{% endfor %}

Upvotes: 2

Alex
Alex

Reputation: 2474

You are, indeed, trying to iterate through an integer.

The first for loop, iterates through results.keys(), that's why you get back those integers which are keys in your first dictionary.

Something like this would work in python:

for x in results:
    for y in results[x]:
        print y

Or, you can use .items() / .iteritems() like this:

for k, v in results.items():
    for small_dict in v:
        print small_dict

Considering that you're trying to do this in a Django template, I think that the first solution would work for you.

Upvotes: 2

Related Questions