How to |int these states and create a simple template

Continuing the discussion from Automation Trigger: list of devices:

trying to use this:

{% set alert_level = states('input_number.battery_alert_level') %}
 {{ expand('group.battery_sensors')
         |selectattr('state', 'lt', alert_level)|list|count}}

won’t work, since the states (of the battery sensors) are strings, and I can’t ‘lessthan’ them even though the template itself is error free. I get the old 100 < 50 = true effect…

Is there no way to make int’s out of these states in the template itself, so I can also int the alert_level, and true numerical evaluation is possible?

thanks if you would have a look please.

{% set alert_level = states('input_number.battery_alert_level')|int %}
{{ expand('group.battery_sensors') 
   | map(attribute='state')
   | map ('int') 
   | select('<', alert_level)
   | list | count }}

think this is the first time I’ve seen that, using map(‘int’), on a previous map(). How on earth did you find that? The things I had tried before I posted this… also, always a bit confusing seeing the attribute ‘state’ :wink: as is select_attr(‘state’,‘lt’,alert_level) for that matter (which you’ve shorthanded as it should be of course, I had tried that, but the string/number issue prevented that from working too)

so, learned 3 more details in jinja today.

I had a need to modify friendly_names. I wanted to remove the trailing word " Door" from each name. I looked through Jinja’s documentation and reviewed the map filter. It included an example where it was used to apply the lower filter to each item in the supplied list.

{{ titles|map('lower')|join(', ') }}

This inspired to use a more complex filter with map that I described in this post:

The key technique was this:

            | map(attribute='name')
            | map('replace', ' Door', '')

Based on that experience, when you asked how to make int’s out of the states, I was reminded of using map.

BTW, there is a limitation to the use of this technique. If your original request was to get a list of entity_id’s for all sensors with a low battery level, this technique cannot be used. That’s because this technique required us to strip away all of the entity’s information except for the state value (in order to perform a numeric comparison). So although it let’s us test one parameter (state), it’s done at the expense of losing all other parameters.