1

I've a list of dictionaries and try to get an attribute of the last entry after a filter. The filtering is working but don't know how to get the attribute.

The template is:

{% set data = [{"key1":1},{"key1":2,"key2":"value"},{"key1":3}] %}
{% if data | selectattr("key1", "equalto", 2) | list %}
elem={{ data | selectattr("key1", "equalto", 2) | list | last }}
attr={{ data | selectattr("key1", "equalto", 2) | list | last | attr("key2") }}
{% endif %}

The output is:

elem={'key1': 2, 'key2': 'value'}
attr=
0

1 Answer 1

0

Found a workaround but no solution so far:

{% set data = [{"key1":1},{"key1":2,"key2":"value"},{"key1":3}] %}
{% for item in data | selectattr("key1", "equalto", 2) | list %}
{% if loop.last %}
elem={{ item }}
attr={{ item.key2 }}
{% endif %}
{% endfor %}

The result is now as expected:

elem={'key1': 2, 'key2': 'value'}
attr=value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.