Removing duplicates in a template

Background:
I have an automation that alerts when someone turns on the thermostat when any exterior windows are open.

I have multiple sensors on most of my exterior doors for redundancy. In most cases there is a YoLink sensor and a Z-Wave sensor. The YoLink sensors are more reliable and need less frequent battery changes, but they depend on the cloud. The Z-wave sensors don’t need the cloud, but I find that between dead batteries and other issues, they just aren’t as reliable as the YoLink stuff overall.

The sensors are named like using this pattern:

  • binary_sensor.master_bedroom_window_z
  • binary_sensor.master_bedroom_window_yo

The automation includes this template as part of the notification:

{% for entity in (expand('binary_sensor.all_window_sensors') 
    | selectattr('state', 'eq', 'on') | list) %}
    {{ entity.entity_id 
      | replace('binary_sensor.', '') 
      | replace('_', ' ') 
      | replace('window z', '')
      | replace('window yo', '')
      | capitalize() 
    }} 
{% endfor %}

The issue is that if the master bedroom window is open, the notification says master bedroom twice. How can I stop this?

Use the unique filter.

However, if you assign an area to your sensors you can use a much simpler template:

{{ state_attr('binary_sensor.all_window_sensors', 'entity_id') 
| select('is_state', 'on') | map('area_name') | unique | list }}

EDIT:

  • Added the state check… :man_facepalming:
  • Fixed select filter.

Thank you for the thoughtful response. I tried your template and the output was:

['Blue Room', 'Family Room', 'Kitchen', 'Master Bedroom', 'Outside', 'Basement']

The only room that actually had an open window was the master bedroom.

If you want a list of areas containing only open windows, you need to use a filter to select only the ones whose state is on.

{{ expand('binary_sensor.all_window_sensors') 
  | selectattr('state', 'eq', 'on')
  | map(attribute='entity_id')
  | map('area_name')
  | unique | sort | list }}

Sorry, I accidentally left out the state check. I have fixed the template in the earlier post.

When I tried that I got:

TemplateRuntimeError: No filter named 'is_state'

That should have been select not map… maybe I should step away from the keyboard for a while.

That worked. Thanks.

123 Taras, your template also worked.

Thanks to you both for the help.

2 Likes

You’re welcome!

Don’t forget to mark Didgeridrew’s post with the Solution tag. It helps other users find answers to similar questions.