Sakeer
Sakeer

Reputation: 2006

Iterating through a dictionary contains both dict and array

Can any one please help me iterate through the below dictionary?

productDict = {
    32L: {
        'width': [9.0, 12.0], 
        'depth': [2,4,6], 
        'height': [5.0,6.0,7.0]
    }, 
    31L: {
        'width': [25.0, 30.0, 35.0, 40.0], 
        'depth': [], 
        'height': []
    }
}

32L and 31L are the id of the products. Each product has width, depth and height...

Upvotes: 0

Views: 74

Answers (2)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

{% for key, l in productDict.items %}
     {{ key }}
     {% for val in l %}
         {{ val }}{% if not forloop.last %},{% endif %}
     {% endfor %} 
{% endfor %}

for django template tag (notice that you use .items to emulate python's .iteritems() on a dictionary)

Upvotes: 0

Victor Castillo Torres
Victor Castillo Torres

Reputation: 10811

Something like:

>>> for key, value in productDict.iteritems():
...      for key2, value2 in value.iteritems():
...                print key2, value2
... 
width [9.0, 12.0]
depth [2, 4, 6]
height [5.0, 6.0, 7.0]
width [25.0, 30.0, 35.0, 40.0]
depth []
height []

Upvotes: 2

Related Questions