Can I count attributes in a sensor without a `for` loop?

This works perfectly for me:

{% set count = namespace(value=0) %}
{% for item in state_attr('sensor.weather_alerts','entries')
   if item.summary |regex_findall('oxfordshire', ignorecase=True) %}
   {% set count.value = count.value +1 %}
   {% endfor %}
{{ count.value }}

For my own education, is there a way to count the number of matching attributes (in an array) without using the loop? I know the following is wrong, but something in this format:

{{ states.sensor
  | selectattr('entity_id','match','sensor.weather_alerts')
  | selectattr('entries.summary','search','Oxfordshire')
  | count
 }}

I have also tried starting with:

{{ expand('sensor.weather_alerts')
  | ...

and

{{ entities.sensor
  | ...

and a few other variations.

Below are the attributes of sensor.weather_alerts. The answer to my query should be 1 as only
{{ state_attr('sensor.weather_alerts','entries')[1].summary }}
contains Oxfordshire:

entries: 
- link: >-
    https://www.metoffice.gov.uk/weather/warnings-and-advice/uk-warnings#?date=2023-08-05&id=2f3d2239-3bfa-4aee-a1cf-a9e050e00b4d&referrer=rss
  summary: >-
    Yellow warning of wind affecting London & South East England: Brighton and
    Hove, East Sussex, Hampshire, Isle of Wight, Portsmouth, Southampton, West
    Sussex valid from 0700 Sat 05 Aug to 1900 Sat 05 Aug
- link: >-
    https://www.metoffice.gov.uk/weather/warnings-and-advice/uk-warnings#?date=2023-08-05&id=6774c084-c4af-4634-b769-91550983e020&referrer=rss
  summary: >-
    Yellow warning of thunderstorm affecting London & South East England:
    Bracknell Forest, Brighton and Hove, Buckinghamshire, East Sussex, Greater
    London, Hampshire, Kent, Medway, Milton Keynes, Oxfordshire, Reading,
    Slough, Surrey, West Berkshire, West Sussex, Windsor and Maidenhead,
    Wokingham valid from 1000 Sat 05 Aug to 2100 Sat 05 Aug

Any pointers would be appreciated.

Try:

{{ states.sensor
  | selectattr('entity_id','match','sensor.weather_alerts')
  | selectattr('entries.summary','search','Oxfordshire')
  | list
  | count
 }}
1 Like
{{ state_attr('sensor.weather_alerts','entries') 
| map(attribute='summary') | select('search', 'Oxfordshire') 
| list | count }}
2 Likes

Thanks, but isn’t that exactly what I wrote?

works perfectly - thanks!

…the key learning for me here is the use of | map(attribute='summary')

No. You did not have |list

But as Drew kindly pointed out you needed more than that.

1 Like

map() is a very handy filter to learn if you want to reduce the number of loops you have to set up. In addition to allowing you to pull out a specific attribute from a list of dictionaries like in this example, it also lets you apply other filters across a list of values.

1 Like

sorry, you’re quite right!

thanks for explaining! Is there any place where I can learn more about it with examples?