Replace part of an attribute name with a variable value

I have a sensor, that has this attribute:
next_best_at: 15, 14, 16, 23, 17, 22, 13, 12, 11, 18, 21, 19, 20

and I save in a variable the first position:

{% set hora = state_attr('sensor.pvpc', 'next_best_at')[0] %}

This saves for example the value 15

And then I have and attribute like this

price_15h: 0.24234

Is is it possible to replace the number in the the attribute name (15 in price_15h), with the variable value set before.

Thank you!

The following template assumes price_15h is an attribute of sensor.pvpc (if it’s not then modify the second line). Copy-paste this into the Template Editor and confirm it reports the correct value.

{% set hora = state_attr('sensor.pvpc', 'next_best_at')[0] %}
{{ state_attr('sensor.pvpc', 'price_' ~ hora ~ 'h') }}
1 Like

Thank you so much @123 ! It worked!

1 Like