Strange behaviour of jinja2 code

The following code gives me a list of datetimes when my automations have been triggered:


But if I append “|sort”, it throws an error. ‘mappingproxy object’ has no attribute ‘last_triggered’
Why is this?

You probably have one or more automations whose state is unavailable (they don’t have a last_triggered attribute).

Try this:

{{ states.automation
   | selectattr('state', 'ne', 'unavailable')
   | map(attribute='attributes.last_triggered')
   | sort }}

You can make it more robust by including this before the map filter:

   | selectattr('attributes.last_triggered', 'ne', None)

Oh, thank you, the solution was so easy!
But why does it complain that there is no attribute “last_triggered”? If the list is already build and I append a sort, it should only sort the list.

It’s a ‘mappingproxy object’

What Taras fixed, but omitted in his explanation is that last_triggered is an attribute, but you’re treating it like a property on the state object (which is a mappingproxy object).

You had (incorrect):

Taras had (correct)

You can read up on state objects here:


Here’s what happens if I eliminate the second line of the template and it encounters the unavailable automations on my test system:

Thank you.
Maybe you can change

So whenever you use this function: 
state_attr(entity_id, ‘attribute’)


So whenever you use this function:
state_attr(entity_id, ‘<attributename>’)

in this article.