Loop through dictionary of lists

Hi, I am new to Django and have a question.

How, in an html file, can I loop through and print items in a list that is within a dictionary?

for example, lets the the dictionary is:
States = {
“California” = [“Los Angeles”, “San Diego”, “Sacramento”]
“Florida” = [“Miami”, “Orlando”, “Ft. Lauderdale”]
“Texas” = [“Dallas”, “St. Antonio”, “Houston”, “Austin”]
}

If I have:
{% for state in States %}

how can I then loop through one state to get the elements in that state (i.e. the cities)?

All help is really appreciate, thanks in advance!

Hi and welcome to the forum!

In Python, dictionaries have a method called items() that will give you keys (in your case the state names) and values (list of cities) together.

So in your template, you should be able to write:

{% for state_name, cities in States.items %}
    {{ state_name }} :
    {% for city in cities %}
        {{ city }}
    {% endfor %}
{% endfor %}

I hope that helps.

Thank you so much, very helpful!

Hi @bmispelon,

I am facing the same issue.
views.py

from django.shortcuts import render
def my_view(request):
    States = {
        'California': ['Los Angeles', 'San Diego'],
        'Florida': ['Miami', 'Orlando'],
        'Texas': ['Dallas', 'St. Antonio']
    }
    return render(request, 'test.html', States)

test.html

<div class="test">
  {% for state_name, cities in States.items %}
      <p>{{ state_name }}</p>
  {% endfor %}
</div>

I followed your reply but still, not able to get the states on the browser.

Please let me know if I am missing anything. [version: Django (3.0.8)]

In your example, you have passed States in as the view’s context. That means that your template will have the states as top level keys (i.e., California would act as a list variable in your template). To make “States” the accessible variable in your template, you need to put it in a context dictionary.

from django.shortcuts import render
def my_view(request):
    context = {}
    context['States'] = {
        'California': ['Los Angeles', 'San Diego'],
        'Florida': ['Miami', 'Orlando'],
        'Texas': ['Dallas', 'St. Antonio']
    }
    return render(request, 'test.html', context)
1 Like

Thanks for the reply, let me try this.