Wracking my brains with this one after spending all morning reading up on dictionaries and how to manipulate them to pull a piece of data from one.
I have a template sensor called sensor.calendar_events that stores the next 12 hours worth of calendar events. That sensor has an attribute calendar_response that contains a dictionary of those events. If I display that attribute in the Developer Tools/Template Editor, I get:
What Iâm trying to achieve is to pull out the number of calendar events in the next 12 hours then feed that into a tts daily briefing announcement followed by the names of the events and the times.
eg "You have 3 events in your calendar today. Swimming starts at 3:45pm and lasts 1 hour. Then you have xxxx starting at x:xx" etc.
How do I select the required objects from the dictionary to slot into my daily briefing file?
I donât need any help with the structure of the briefing, Iâve got that sorted. I just need to know how to get the right piece of data from the dictionary.
From a post in this community on extracting objects from dictionaries, I understand which is the â0â attribute and which is the â1â attribute and the concept of tuples (well I think I do), but I think the
{
"events": [
{
object is adding another layer of complexity Iâm not able to master.
This is how the sensorâs attributes are displayed:
That is because as_timestamp expects a datetime string or object, not a list. You can use map() to apply filters across all the members of an object or items in a list:
{{ state_attr('sensor.calendar_events', 'calendar_response')['events']
| map(attribute='start') | map('as_timestamp') | list }}
But that might not be the best way to approach it for your expressed goalâŚ
{% set e_list = state_attr('sensor.calendar_events', 'calendar_response')['events']
| sort(attribute= 'start') | list %}
You have {{ e_list | count }} events in your calendar today.
{% if e_list | count > 0 %}
{%- for e in e_list %}
{{ ['Then you have ','Next is ', 'Followed by ']|random if not loop.first else ['First up is ', 'First is ']|random}}
{{- e.summary }} at {{ (e.start|as_datetime).time() }} {{-[' for ', ' lasting for ', ' that lasts ']|random}}{{- (e.end|as_datetime - e.start|as_datetime).total_seconds()/3600 }} hours.
{%- endfor %}{% endif %}