Jinja2 reject/select filter and sorting out zero values in list

Hi!
I have a template sensor, which renders average temperature at my house.

- platform: template
  sensors:
    temperature_home:
       value_template: >
        {% set temperatures = [
               states("sensor.temp1") | float,
               states("sensor.temp2") | float,
               states("sensor.temp3") | float
           ] %}
        {{ (temperatures | sum / temperatures | count) | round(1) }}

Works pretty good, but sometimes one of the sensors shows 0 value (looks like a problem with Netatmo platform) and an average value becomes wrong. I’m trying to sort out zero values, but haven’t found a simple solution yet. I tried

{{ (temperatures | sum / (temps | reject("==","0") | count)) }}

reject jinja2 filter should return a list without zero values, but instead it returns <generator object select_or_reject at ...> and doesn’t work with count filter.
Does anybody familiar with how reject (or select) filter works? Or maybe my issue could be solved even simplier)

its expecting this to be in a for loop, it can’t be used like this. Luckly there’s another filter that will work for you on top of that, the ‘list’ filter. It turns generators into lists.

{{ mylist | reject("==", 0) | list }}

Just make sure you don’t put 0 in quotes because that will be looking for strings. So in your example:

{% set temps = temperatures | reject("==", 0) | list %}
{{ ( temps | sum / temps | count ) | round(1) }}

EDIT: I fixed it again. This should work.

2 Likes

Thanks! It works.
Just a little mistake here:

{% set temps = temperatures | reject("==", 0) | list %}
    ^
1 Like

ah yep, ill edit my post for future goers

Is there any documentation on how select and/or reject work? I am trying to find all switches whose object_id starts with a certain string, and return true if any of them are on – basically the functionality of a group.

I’m imagining it’s something like this:

{%- set switches = states.switch 
  | map(attribute='entity_id') 
  | select('startswith', 'switch.multipower1_')
  | list -%}

According to Jinja2’s documentations, select supports all built-in tests.

There’s no ‘startswith’ (or equivalent) test in that list and the closest one (but not very) is in.

I was hoping I could use a template to accomplish this, but I just ended up using a group. Oh well.