The following code works in ‘Developer Tools|Template’-Playground:
{% set ns = namespace() %}
{% set ns.morning_prices = {} %}
{% set ns.mean = 0 %}
{% set ns.total_counter = 0 %}
{% for i in range ( 0, int(states('sensor.hour_of_sunrise')) ) %}
{% set ns.mean = ns.mean + ((states.sensor.current_spot_electricity_hour_order.attributes.values()|list)[i]).1 | float %}
{% set ns.total_counter = ns.total_counter + 1 %}
{% set ns.morning_prices = dict(ns.morning_prices, **{(states.sensor.current_spot_electricity_hour_order.attributes|list)[i]:(states.sensor.current_spot_electricity_hour_order.attributes.values()|list)[i]}) %}
{% endfor %}
{% set ns.mean = ns.mean / ns.total_counter %}
ns.morning_prices {{ ns.morning_prices }}
ns.mean {{ ns.mean }}
and does show the result as of:
ns.morning_prices {'2024-11-27T00:00:00+01:00': [6, 3.213], '2024-11-27T01:00:00+01:00': [5, 3.033], '2024-11-27T02:00:00+01:00': [2, 2.818], '2024-11-27T03:00:00+01:00': [3, 2.866], '2024-11-27T04:00:00+01:00': [4, 2.98], '2024-11-27T05:00:00+01:00': [7, 3.519], '2024-11-27T06:00:00+01:00': [10, 3.906], '2024-11-27T07:00:00+01:00': [22, 4.471]}
ns.mean 3.35075
transferring this into template.yaml
sensor:
- name: morning_prices
state: >
{% set ns = namespace() %}
{% set ns.morning_prices = {} %}
{% set ns.mean = 0 %}
{% set ns.total_counter = 0 %}
{% for i in range ( 0, int(states('sensor.hour_of_sunrise')) ) %}
{% set ns.mean = ns.mean + ((states.sensor.current_spot_electricity_hour_order.attributes.values()|list)[i]).1 | float %}
{% set ns.total_counter = ns.total_counter + 1 %}
{% set ns.morning_prices = dict(ns.morning_prices, **{(states.sensor.current_spot_electricity_hour_order.attributes|list)[i]:(states.sensor.current_spot_electricity_hour_order.attributes.values()|list)[i]}) %}
{% endfor %}
{% set ns.mean = ns.mean / ns.total_counter %}
{{ ns.total_counter }}
unit_of_measurement: "Kcs"
attributes:
morning_prices: "{{ ns.morning_prices }}"
will result in ‘unavailable’ state
This code should deliver a dict of energyprices between 0 and 8 o’clock (actual status of hour_of_sunrise) and the mean price.