Default value when attribute is missing (or other way to solve this)

The weather report has changed now which means it reports at 02:00, 08:00 and not 01:00 and 07:00 as last week.
But instead of just patching it, I figure I can do better and get the weather at both 07:00 and 08:00 (perhaps 09:00, and 06:00 just to be sure).

But the issue is that I can’t use default value when the attribute is missing.

The template is getting mondays weather report on friday, that is why the report is not detailed enough to have all hours.

{%- set dt2 = ((today_at("07:00")+timedelta(days = 7-now().weekday()))| string)[0:16] -%}
         ^^
{%- set aa = state_attr('sensor.smhi_hourly', 'hourly')[dt2]['nederbord'] | float(0) %}
                                                         ^^
{%- if aa  > 1 -%}
  True
{% else %}
  False
{%- endif -%}

above is the simplified version, but what I want is to check if the attribute is there then use it, if not then either return 0 or somehow if attribute missing then.
The float(0) does not seem to make any difference, when I run the automation it reports Error rendering data template: UndefinedError: "dict object" has no attribute '2024-04-01 07:00'
And that is true but shouldn’t aa have become 0.0?

{% set aa = state_attr('sensor.smhi_hourly', 'hourly').get(dt2,{}).get('nederbord',0)|float(0) %}

Effectively two checks going on here. This first get() looks for the dt2 key and returns an empty dictionary if not found. That feeds the second get(), which looks for the 'nederbord' key, returning 0 if it’s not found.

1 Like