Search code examples
pythondjangodjango-templatesordereddictionarytemplatetags

django - showing OrderedDict in templatetag


I have a OrderedDict and I need to show its key, value but I am unable to get its value, I have this dict = ([('sainbath', 'thesailor'), ('HELLO', 'WORLD')]), I have tried this

{{object.specifications}}
      <ul>
        <li>{% for key in object.specifications %}
          {{key}}
          {%endfor%}

I am getting this output

OrderedDict([('sainbath', 'thesailor'), ('HELLO', 'WORLD')])

  • sainbath HELLO

I am getting its key only not value, when I tried this

{{object.specifications}}
      <ul>
        <li>{% for key,value in object.specifications %}
          {{key}} : {{value}}
          {%endfor%}

it give me error

Need 2 values to unpack in for loop; got 8. please tell me how can I get value?


Solution

  • 1) Use following in template:

    {% for key,value in object.specifications.items %}
          {{key}}:{{value}}
    {% endfor %}
    

    OR

    2)If you are rendering a template with the data as OrderedDict, you can use following approach for the same.

    return render_to_response('your_template.html',{'data': sorted(your_ordered_dict.iteritems())})
    

    and in Template you can use the same as below:

    {% for key, value in data %}
         {{key}}:{{value}}
    {% endfor %}
    

    Hope it will help you!!