Use selectattr to filter on numeric states

I apologize if this was already answered in the forum, but Ireally was not able to find a solution for my issue.

I’ve used this nice automation from @Didgeridrew to notify about my family’s birthdays, and works perfectly.

However I now need another automation to notify some days before the birthday. However, since states are always string, I cannot use arithmetic operators inside the selectattr.

Thus, I used map to extract the state and convert to int, before filtering.

{{ expand('sensor.faimily_birthdays')
| rejectattr('state', 'in', ['unavailable','unknown', 'off'])
| map(attribute='state')
| map('int', 0)
| map('<', 3)
| list }}
}}

Howerer, this gives me an array of state integer values, while a need the entire entities list instead.

I was wondering if there is a way to get this as a list directly, or at least to have a boolean array with [true, false] values to use then to filter the starting group instead.

tnx allot for any suggestion!

You’re making this more complicated than it needs to be. There have been a few additions to the available template filters that make it even easier than shown in that prior post. Now we can just select items whose state attribute is in the list ['0', '1', '2', '3'] by using the is_state test.

{{ state_attr('sensor.faimily_birthdays', 'entity_id')
| select('is_state', ['0','1','2','3']) | expand | list }}

If you wanted to check against a larger range of sequential numerical values, you can use a little trick to turn a range into a list of number strings, so you don’t have to type them all. A 10 day range would be as follows:

{% set my_range = range(0,11) | map('string') | list %}
{{ state_attr('sensor.faimily_birthdays', 'entity_id')
| select('is_state', my_range) | expand | list }}

That’s a lovely solution! I really didn’t think about using discrete lists instead of integers.

Afterall, I have just a wife and two kids :smiley:

tnx allot!

FWIW, you can use integers… it’s just a longer template:

{% set sensor_list = state_attr('sensor.faimily_birthdays', 'entity_id') %}

{% set in_range = sensor_list 
| reject('is_state', ['unavailable','unknown', 'off']) | map('states') 
| map('int', 0) | select('<=', 3) | map('string') | list %}

{{ sensor_list | select('is_state', in_range) | expand | list }}
1 Like

Also note that we now have the zip function available with version 2024.9, so another alterative is:

{% set sensor_list = state_attr('sensor.faimily_birthdays', 'entity_id') %}
{% set sensor_states_list = sensor_list | map('states') | map('float', 999) | list %}

{{ zip(sensor_list, sensor_states_list) | selectattr(1, '<=', 3) | map(attribute=0) | list }}
4 Likes