How to loop through binary_sensors AND sensors?

Good afternoon, I’m desperately trying to loop through binary_sensors and normal sensors at the same time. The goal is to display all my dead batteries. How can i achieve this? I’ve gotten so far… but unfortunately i don’t understand how to add two kinds of sensors in the “for” loop:

{% set result = namespace(low=[]) %}             
  {%- for state in states.binary_sensor if state.entity_id.endswith("_battery") -%}               
    {%- if state.state == "unavailable" -%}                   
  {% set result.low = result.low + [ state.name ] %}               
{%- endif -%}

e.g. this doesn’t work
for state in states.binary_sensor or state in states.sensor ....

Ofc, i can use a workaround like this, but it’s ugly

{% set result = namespace(low=[]) %}             
{%- for state in states.binary_sensor if state.entity_id.endswith("_battery") -%}               
  {%- if state.state == "unavailable" -%}                   
    {% set result.low = result.low + [ state.name ] %}               
  {%- endif -%}             
{%- endfor -%}
           
{%- for state in states.sensor if state.entity_id.endswith("_battery") -%}               
  {%- if state.state == "unavailable" -%}                   
    {% set result.low = result.low + [ state.name ] %}               
  {%- endif -%}             
{%- endfor -%}

Thanks for your help!

It can be done without the use of a for-loop. Here are two examples:

{{ expand(states.sensor, states.binary_sensor) 
  | selectattr('state', 'eq', 'unavailable')
  | map(attribute='name') | list }}
{{ expand(states.sensor, states.binary_sensor)
  | selectattr('object_id', 'search', '_battery$')
  | selectattr('state', 'eq', 'unavailable')
  | map(attribute='name') | list }}
1 Like

Amazing @123 , that did the trick. Here is my solution to output this as a message.
Now i’m happy with this clean and compact code :slight_smile: thanks again!

{% set result = expand(states.sensor, states.binary_sensor)
| selectattr(‘object_id’, ‘search’, ‘_battery$’)
| selectattr(‘state’, ‘eq’, ‘unavailable’)
| map(attribute=‘name’) | list %}
Check the following Sensors: {{ result | join(', ')}}

1 Like