[Answered ]-Python – find first dictionary key in template

1πŸ‘

βœ…

What I finally done was as following:

creating an OrderedDict out of my Dictionary, making sure that it’s sorted by dates Descending:

 duration_dict = OrderedDict(sorted(duration_dict.items(), key=lambda t: t[0], reverse=True))

So now I can be sure that the first key is also the latest year.
and for presenting all the key,value pairs without the first year I used forloop.first, as suggested by @bozdoz:

{% for year, durations in duration_dict.items %}
                            {% if not forloop.first %}
                            <optgroup label={{ year }}>
                            {% endif %}
                           {% for duration in durations %}
                              <option data-from-date="{{ duration.from_date }}" data-to-date="{{ duration.to_date }}" value={{ duration.duration_id }}>{{ duration.from_date }}
                                - {{ duration.to_date }}</option>
                            {% endfor %}
                        {% endfor %}
πŸ‘€user2880391

1πŸ‘

If you don’t want to show the first iteration of a for loop in a Django template, you can omit it by checking for forloop.first

 {% for year, durations in durationDict.items %}
      {% if not forloop.first %}
      <optgroup label={{ year }}>
      {% for duration in durations %}
           <option data-from-date="{{ duration.from_date }}" data-to-date="{{ duration.to_date }}" value={{ duration.duration_id }}>{{ duration.from_date }}
                                - {{ duration.to_date }}</option>
      {% endfor %}
      {% endif %}
 {% endfor %}
πŸ‘€bozdoz

0πŸ‘

You can use a filter tag. For example:

template_tags.py

from django import template


register = template.Library()

@register.filter()
def exclude_first(dict):
    first_key = list(dict)[0]
    del dict[first_key]
    return dict

html

{% load template_tags %}

{% for year, durations in durationDict|exclude_first %}
...
{% endfor %}

This should allow you to loop through all of the items in durationDict except for the first item. Keep in mind that dicts are not ordered by default. If you have a custom key/value pair that you want deleted every time, you can simply replace del dict[first_key] with del dict['latest_year'] (or replace latest_year with the key name you want to delete).

πŸ‘€Hybrid

Leave a comment