Searching sensors with selectattr

I am trying in vain to list all sensors that either start with sensor.stock_ for a calculation. Or which contain the attribute ‘typ’.
For example, I can retrieve the value for {{ states.sensor.stock_biontech.attributes.typ }} without error. But I do not get any value for

{% set entities = states.sensor
  | selectattr('entity_id', 'match', 'sensor.stock_.*')
  | list %}

And I get an error when I search for ‘typ’:
selectattr('attributes.typ', 'eq', '123').
It reports that there is no sensor with attribute ‘typ’, which is certainly not true.

Copy-paste the following template into the Template Editor and confirm it reports what you want.

{% set entities = states.sensor
  | selectattr('object_id', 'match', 'stock_')
  | map(attribute='entity_id')
  | list %}
{{ entities }}

Thank You! Is it also possible to filter for a attribute? E.g. custom_color?
{{ states.sensor|selectattr('attributes.custom_color','eq','red')|list|count }} gives me UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'custom_color'
But there are entities with custom_color:

If I do {% set count = states | selectattr('attributes.custom_color', 'defined') | selectattr('attributes.custom_color', 'eq', 'red') | list | count %} , I get no error, but also no results.
Also with correct typo:

Uups, I forgot the {{ count }} :see_no_evil:
Works now!
And I managed to get the sum of the attributes:

{% set entities = states.sensor 
  | selectattr('attributes.custom_color', 'defined')
  | selectattr('object_id', 'match', 'stock_')
  | selectattr('attributes.custom_color', 'eq', 'red') 
  | list %}
{#{ entities }#}
{% set sum = entities
  | map(attribute='attributes.price')
  | map('replace', ',', '.')
  | map('float')
  | sum %}
{{ sum }}

The Solution tag is assigned to the post that answers/corrects the original question/problem (not subsequent questions/problems that introduce additional complexity to the original question/problem). You asked how to list all sensors starting with a given string and I showed you how to do that correctly. That’s the Solution.

The Solution tag is meant to lead other users, looking for an answer to “Searching sensors with selectattr”, to the first post that shows how to do it. For more information about the Solution tag, refer to guideline 21 in the FAQ.

i’m sorry and thank you for the information, i hadn’t paid attention to that. that was indeed the decisive hint. but i’ve just corrected it.

1 Like