Templates in command line sensor + Octopus Energy API

After seeing the value_template you created, it made me wonder if there was a way in Jinja2 to make it more compact.

At first I jumped on the idea of using a for-loop. Just iterate through all the consumption values and add them up. Unfortunately, the latest version of Jinja2 (2.10) has tightened up its scoping rules and, long story short, you can’t calculate the sum using a for-loop.

Today I saw this post and thought it was not only clever but a potential solution for making your value_template more compact.

It performs its magic using map and sum. The map creates a list containing the desired attribute values and then sum adds up all entries in the list. Very neat!

Using the Template Editor, I created some data and then tested the template.

{% set x = {"results":[{"consumption": 10}, {"consumption": 20}, {"consumption": 30}, {"consumption": 40}, {"consumption": 50} ]} %}

{{ x.results | map(attribute="consumption") | sum }}

The result is 150 as would be expected from 10+20+30+40+50.

I don’t have access to the actual data you are using so I can’t confirm that what I have to offer will instantly work for you. Here it is:

    value_template: '{{ (state_attr("sensor.gas", "results") | map(attribute="consumption") | sum / 11.36) | round(3)}}'

If it doesn’t work, please give me the data from your state_attr('sensor.gas', 'results') and I’ll make it work.


EDIT
As expected, the suggested template did contain an error and has now been corrected as per ajoyce’s suggestion.

3 Likes