I have been struggling all day to achieve a simple thing, several AIs could not help me fix it.
I am trying to create a sensor that shows me the most likely weather forecast for the next 4 hours. I just want to grab the forecasts and determine which element appears most often.
So for example:
[‘sunny’, ‘sunny’, ‘sunny’, ‘rainy’] should result in ‘sunny’
[‘sunny’, ‘sunny’, ‘rainy’, ‘rainy’] should result in ‘inconclusive’
I think this transports my point, if one condition occurs more often than all the others, that one wins, otherwise its inconclusive.
I was successful in extracting this array with 4 strings, but was not able to implement the remaining functionality. Any help is appreciated. Here is how I did it:
template:
- trigger:
- platform: state
entity_id: weather.forecast_home
action:
- service: weather.get_forecasts
data:
type: hourly
target:
entity_id: weather.forecast_home
response_variable: hourly
sensor:
- name: Local Weather Forecast Hourly
unique_id: local_weather_forecast_hourly
state: "{{ now() }}"
attributes:
forecast: "{{ hourly['weather.forecast_home'].forecast }}"
- sensor:
- name: "Most Likely Weather Next 4 Hours"
unique_id: most_likely_weather_next_4_hours
state: >
{% set forecast_list = state_attr('sensor.local_weather_forecast_hourly', 'forecast') | default([]) %}
{% set conditions = forecast_list | map(attribute='condition') | list %}
{% if conditions | length > 4 %}
{% set conditions = conditions[:4] %}
{% endif %}
{% set condition_counts = {} %}
{% for condition in conditions %}
{% set condition_counts = condition_counts | merge({ condition: (condition_counts[condition] | default(0)) + 1 }) %}
{% endfor %}
{% set most_likely_condition = condition_counts | dictsort(true, 'value') | first %}
{{ most_likely_condition[0] }}
This fails: TemplateAssertionError: No filter named ‘merge’. All other attempts to create this dictionary also failed.