Indradhanush Gupta Indradhanush Gupta - 3 months ago 14
Python Question

How do I read a nested dictionary in a Django template?

I am trying to access the following data structure inside a template in Django. But its too difficult for me too figure out how.

{ Day1 : { Room1 : [(datetime.date(), (totalTime1, Flag1)),
(datetime.date(), (totalTime2, Flag2)),
(datetime.date(), (totalTime3, Flag3)),
(datetime.date(), (totalTime4, Flag4))],

Room2 : [(datetime.date(), (totalTime1, Flag1)),
(datetime.date(), (totalTime2, Flag2)),
(datetime.date(), (totalTime3, Flag3)),
(datetime.date(), (totalTime4, Flag4))],

Room3 : [(datetime.date(), (totalTime1, Flag1)),
(datetime.date(), (totalTime2, Flag2)),
(datetime.date(), (totalTime3, Flag3)),
(datetime.date(), (totalTime4, Flag4))] },

Day2 : { Room1 : [(datetime.date(), (totalTime1, Flag1)),
(datetime.date(), (totalTime2, Flag2)),
(datetime.date(), (totalTime3, Flag3)),
(datetime.date(), (totalTime4, Flag4))],

Room2 : [(datetime.date(), (totalTime1, Flag1)),
(datetime.date(), (totalTime2, Flag2)),
(datetime.date(), (totalTime3, Flag3)),
(datetime.date(), (totalTime4, Flag4))],

Room3 : [(datetime.date(), (totalTime1, Flag1)),
(datetime.date(), (totalTime2, Flag2)),
(datetime.date(), (totalTime3, Flag3)),
(datetime.date(), (totalTime4, Flag4))] } }


Probably its a very complex data structure, but I am sorry about it. I couldnt break it up. My choice is limited.
I want to access each element in a single loop. How may I do it?

Edit : I want to access the elements from a django template.

Answer

It can't be done in a single loop, but you can do it with some nesting:

{% for day, rooms in mydict.items %}
  {% for room, dates_and_flags in rooms.items %}
    {% for date, time_and_flags in dates_and_flags %}
        {{ date }}:{{ time_and_flags }}
    {% endfor %}
  {% endfor %}
{% endfor %}

Because time_and_flags is a tuple, you can access the time using time_and_flags.0 and the flags with time_and_flags.1.