Intersection of two lists in jinja templates for condition?

How to intersect two lists in HA jinja templates? The goal is to return single boolean value, so it can be used in conditions.

Example:

{% set my_test_json = {
  "list1": ["a1", "a2", "b1", "b2"],
  "list2": ["a2", "b2", "c2", "d2"]
} %}

How to return true if there are common elements between list1 and list2 or false otherwise?

Thanks!

You only need to loop one of the lists.


{% set ns = namespace(bool=false) %}

{% for val in my_test_json.list1 %}
  {% if val in my_test_json.list2 %}
    {% set ns.bool = true %}
  {% endif %}
{% endfor %}

{{ ns.bool }}
1 Like

That’s a working solution, thanks!

Would be nice to have some basic list/set operations available for HA template engine.

{{ (list1 + list2) | count != dict.fromkeys(list1 + list2) | count }}

NOTE

This works only if there are no duplicate values within a list. For example, list1 cannot have more than one instance of a2. If it does then the suggested template will produce an incorrect result. If there’s a possibility that either list can contain duplicates within it then use the example Hellis81 provided.

1 Like