How to count sensors based on attribute?

Is it possible to count the number of sensors that has the same icon attribute?

Tried the template below in the editor but got

TypeError: object of type ‘generator’ has no len()

{{ states.binary_sensor | selectattr( 'icon', 'eq', 'mdi:cloud' ) | count }}

The correct filter for your use case is not count, but length.

https://jinja.palletsprojects.com/en/3.1.x/templates/#jinja-filters.length

Thanks, but I get the same result with length, should it be formatted differently?

{{ states.binary_sensor | selectattr( 'icon', '==' 'mdi:cloud' ) | length }}

And the following returns “0”

{{ states.binary_sensor | selectattr( 'icon', 'eq', 'mdi:cloud' ) | list | length }}

Try attributes.icon, maybe?

(You’ll need |list, yes…)

1 Like

That did it, thanks.

{{ states.binary_sensor | selectattr( 'attributes.icon', '==', 'mdi:cloud' ) | list | length }}

Tried using the above to create a template sensor, but it doesn’t seem to populate.

sensor:
  - platform: template
    sensors:
      cloud_sensors:
        friendly_name: "Cloud Sensors"
        value_template: "{{ states.binary_sensor | selectattr( 'state', '==', 'on' ) | selectattr( 'attributes.icon', '==', 'mdi:cloud' ) | list | length }}"

template:
  - sensor:
      - name: "Cloud Sensors"
        state: >
          {{ states.binary_sensor | selectattr( 'state', '==', 'on' ) | selectattr( 'attributes.icon', '==', 'mdi:cloud' ) | list | length }}