How to get the first entry in a for loop

Hello,

i trying to get only the first entry in a for loop,

{% for entity in  expand('group.diesel_fuel_sensors') | sort(attribute='state') | map(attribute='entity_id') | map('string')  | list %}
  {{states(entity)}} €
  {% endfor%}

thats a re my results

1.759 €
  
  1.799 €
  
  1.819 €

thank you

hi,
try this.

{% for entity in  expand('group.diesel_fuel_sensors') | sort(attribute='state') | map(attribute='entity_id') | map('string')  | list %}
  {%- if loop.first %}
  {{states(entity)}} €
  {% endif -%}
{% endfor%}

While it’s probably not going to cause an issue in this case, be aware that states are always strings so your sort is based on string comparison not a true numeric comparison.

{{ expand('group.diesel_fuel_sensors') 
| sort(attribute='state') 
| map(attribute='state')  | list | first }} €

In cases where you need a true numeric comparison, you can map the the states to a float before the sort:

{{ expand('group.diesel_fuel_sensors')  
| map(attribute='state')  | map('float', -1) 
| reject('lt', 0 ) | sort() | list | first }} €
1 Like

so one could do a ‘sort’ in-between then?
EDIT, sorry as not wanting to hijack the OP question but would max/min also work in string?
i.e. if I sort the list ascending and take the first, this would be ‘equal’ to min …or? (and vv for max)

Yes, OP could use min or max

{{ expand('group.diesel_fuel_sensors') 
| map(attribute='state') | list | min }} €

Again if you map() to a float, the warning about string comparison no longer applies, but make sure to set a default that gives you a way to reject ‘unknown’ or ‘unavailable’ states.

{{ expand('group.diesel_fuel_sensors') 
| map(attribute='state') | map('float', -1)
| reject('lt', 0 ) | list | min }} €
1 Like

thank you that works well,
is it possible to display the attribute “station_name” which is related to the entity that displays the price?

I’ve tried a few things, but I always get “zero”.

here is for example one of the entities in the group

When you map to an attribute you effectively throw away all the other data from the state objects. You can use a second statement to select the proper entity based on the state derived from the first one.

{% set x = expand('group.diesel_fuel_sensors') 
| sort(attribute='state') | map(attribute='state') | list | first %}
{{ expand('group.diesel_fuel_sensors') 
| selectattr('state', 'eq', x) | map(attribute='attributes.station_name') | list | first }}

However, since the string comparison shouldn’t be an issue in your case, I would approach it as follows:

{% set x = expand('group.diesel_fuel_sensors') 
| sort(attribute='state') | list | first %}
{{ x.attributes.station_name }}
1 Like

ah okay i didn’t know that, that’s very helpful the information that he discards all other data.

Thank you very much that helped me a lot.