Template get name of sensor with highest Co2 value, value

I’m stuck with a template sensor. I want to get the name from a group of sensor which has the highest Co2 value.

here’s the template;

{{expand(
'sensor.zolder_slaapkamer_zolder_slaapkamer_zolder_slaapkamer_zolder_wc_co2',
'sensor.xxxx_kamer_co2',
'sensor.xxxx_kamer_xxxx_kamer_xxxx_kamer_office_co2',
'sensor.livingroom_bathroom_co2',
'sensor.livingroom_livingroom_livingroom_masterbedroom_co2',
'sensor.livingroom_livingroom_livingroom_kamer_co2',
'sensor.livingroom_co2') 
| selectattr('state', 'is_number')
| sort(attribute='state', reverse=true)
| map(attribute='state')
| list
}}

The result of the template is;
[


  "993",
  "792",
  "739",
  "622",
  "496",
  "454",
  "1020"
]

I would expect the last value to be the first value;

[
  "1020",
  "993",
  "792",
  "739",
  "622",
  "496",
  "454"
]

But for some reason I can’t get it to work…
For debugging I map the state and do |list in the final version that will be the name and |first.
It’s probably something very simple, but I don’t see it :expressionless:

found that’s a string sort and solved it another way;

{% set ns = namespace(s=[]) %}
{% for x in expand('sensor.zolder_slaapkamer_zolder_slaapkamer_zolder_slaapkamer_zolder_wc_co2',
'sensor.roos_kamer_co2',
'sensor.roos_kamer_roos_kamer_roos_kamer_office_co2',
'sensor.livingroom_bathroom_co2',
'sensor.livingroom_livingroom_livingroom_masterbedroom_co2',
'sensor.livingroom_livingroom_livingroom_maaike_kamer_co2',
'sensor.livingroom_co2')  %}
{% set ns.s = ns.s + [(x.name, x.state|int)] %}
{% endfor %}

{% set sorted = dict.from_keys(ns.s)|dictsort(false, 'value', reverse=true) -%}
{{ sorted[0][0]}}

Another way, if all your CO2 sensors contain _co2 in the entity ID, and no other sensors do:

# build a list of entity IDs
{% set sl = states['sensor']|map(attribute='entity_id')|select('contains','_co2')|list %}

# build a list of their states
{% set ssl = sl|map('states')|map('float', default=0)|list %}

# find the maximum
{% set sm = ssl|max %}

# find the corresponding entity ID
{% set sn = sl[ssl.index(sm)] %}

{{ sn }}: {{ sm }}
1 Like