Sort values in entity attribute

I have entity “sensor.current_market_price_czk_kwh”. One of attributes, called “today_hourly_prices” contains 24 numbers, which represents energy prices in the hour.

today_hourly_prices: 2.76, 2.6, 2.5, 2.51, 2.59, 2.73, 2.67, 2.59, 1.93, 0.38, 0, -0.18, -0.48, -0.78, -0.62, 0.19, 0.99, 1.69, 3.13, 3.61, 3.26, 2.56, 2.34, 1.62

I need assign hour to every price and sort those prices from lowest to highest.
I have no idea, how to do that. Help me, plese.

Before you get too far in the weeds, you might want to check if the Cheapest Energy Hours macro does what you want and works with your source sensor.

Otherwise you can take a look at the following:

{% set price_list = state_attr('sensor.current_market_price_czk_kwh', 'today_hourly_prices') %}
{% set ns = namespace(hour_price=[])%}
{% for price in price_list %}
  {% set ns.hour_price = ns.hour_price + [dict(hour=loop.index-1, price=price)] %}
{% endfor %}
{{ ns.hour_price | sort(attribute='price') | list }}
1 Like

Exactly, that’s it :slight_smile: . Thank you very much.

1 Like