Create a real-time list of 4 highest consumption devices

I have 15 power sensors measuring the consumption of 15 different devices. I want to show the 4 or 5 highest-cunsumption devices in real time in Lovelace.

I’ve tried min-max, statistics, etc., but they don’t seem to solve what I’m looking for. Anybody can point me in the right direction? Thanks.

Copy-paste the following template into the Template Editor and experiment with it.

{% set ns = namespace(sensors=[]) %}
{% for s in states.sensor
  | selectattr('attributes.device_class', 'defined')
  | selectattr('attributes.device_class', 'eq', 'power')
  | rejectattr('state', 'in', ['unavailable', 'unknown'])
  | list -%}
  {% set ns.sensors = ns.sensors + [{"id": s.entity_id, "state": s.state|int(0)}] %}
{% endfor %}

{% for s in (ns.sensors | sort(attribute='state', reverse=true))[:4] -%}
{{ s.id }}, {{ s.state }}
{% endfor %}

EDIT

Correction. Truncate list produced by first for-loop as opposed to within it.

Shouldn’t the list be limited to 4 after sorting?

{% set ns = namespace(sensors=[]) %}
{% for s in (states.sensor
  | selectattr('attributes.device_class', 'defined')
  | selectattr('attributes.device_class', 'eq', 'power')
  | rejectattr('state', 'in', ['unavailable', 'unknown'])
  | list) -%}
  {% set ns.sensors = ns.sensors + [{"id": s.entity_id, "state": s.state|int(0)}] %}
{% endfor %}

{% for s in (ns.sensors | sort(attribute='state', reverse=true))[:4] -%}
{{ s.id }}, {{ s.state }}
{% endfor %}

This definitely looks like the way to go, I’ll start working from there. Two quick questions: Can the code be modified to point only ant the 15 sensors I want to monitor? Can I choose what sensor in the list I show? (Let’s say the third sensor in the top 5 devices, per consumption). Thanks.

Yes, good point. The example I posted went through several iterations and the [:4] got moved around several times … and ended up in the wrong place.

I have corrected the example posted above.

Yes.

{% set ns = namespace(sensors=[]) %}
{% for s in expand('sensor.one', 'sensor.two', 'sensor.etc')
  | rejectattr('state', 'in', ['unavailable', 'unknown']) -%}
  {% set ns.sensors = ns.sensors + [{"id": s.entity_id, "state": s.state|int(0)}] %}
{% endfor %}

{% for s in (ns.sensors | sort(attribute='state', reverse=true))[:4] -%}
{{ s.id }}, {{ s.state }}
{% endfor %}