Hi.
Is it possible to somehow search/loop through an array/dictionary from last to first? (bottom → top)
Any help appreciated!
Hi.
Is it possible to somehow search/loop through an array/dictionary from last to first? (bottom → top)
Any help appreciated!
Typical… I think I may have found the solution to my problem just after I created this topic.
{%- for item in search | reverse() %}
What is the precise use-case you have in mind?
I’m asking because there are pythonic means of finding an item in a list that don’t require an explicit for-loop.
Copy-paste the following in the Template Editor and experiment with it.
{% set x = ['red', 'yellow', 'green', 'blue', 'black'] %}
{{ x }}
{{ 'blue' in x }}
{{ x.index('blue') }}
{{ x | reverse | list }}
{{ x[::-1] }}
{{ 'blue' in x[::-1] }}
{{ x[::-1].index('blue') }}
If the goal of reversing the list is to reduce search time for items at the end of list, don’t forget that reversing the list also adds processing time. That’s why I’m curious to know what’s your application that requires list reversal before performing a search.
Ah, this is very interesting… Thank you for taking the time to explain all this.
I’m trying to search for a specific item in an RSS feed. (which has multiple items with the same name)
The top items in the feed are the newest, but a regular ‘for’ loop would, in my case, get multiple hits and end up picking the last item.
Reversing the list would have the same effect, but now the last item picked is the newest in the RSS feed.
Post an example of the data that you intend to search for a specific item.
BTW, you can use Jinja2 filters to extract items from a list or dict. For example, this creates a list containing the the three ‘red’ items.
{% set x = ['red', 'yellow', 'green', 'red', 'blue', 'black', 'red'] %}
{{ x | select('eq', 'red') | list }}