Checking value is in a list of dictionary values in Jinja

Question:

I have a list of tables coming from a SQLite database:

tbls_name = db_admin.execute(
    """SELECT name FROM sqlite_master WHERE type='table';"""
)

And need to check if table_name is in the resulting list of dictionaries.

In Python, I would do:

if table_name in [d['name'] for d in tbls_name]:

How can I do this in Jinja?

{% set tbl_valid = (table_name in [d['name'] for d in tbls_name]) %}

This throws an error.

Note that the tbls_name is a list of dictionaries, e.g.:

[
    {'name': 'tableName1'},
    {'name': 'tableName2'},
    {'name': 'tableName3'},
]
Asked By: parmer_110

||

Answers:

You can use the filter rejectattr for this use case.
If the resulting list of dictionary still contains any item, then the queried table name is valid.

{% set tbls_name = [
  {'name': 'foo'},
  {'name': 'bar'},
  {'name': 'baz'},
] -%}
{% set tableName = 'foo' -%}

{% if tbls_name | rejectattr('name', '!=', tableName) | list | length -%}
  table name `{{ tableName }}` is valid
{% endif %}

Would yield:

table name `foo` is valid 
Answered By: β.εηοιτ.βε
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.