Get sublist of dictionaries based on attribute condition

Viewed 82

I have this list of dictionaries:

some_list:
  - name: alfa
    dir: aaa
  - name: beta
    dir: bbb
  - name: gamma
    dir: ggg

and I want to get, via Ansible/Jinja, a subset of some_list, should still be a list, which only contains the dicts having name in ['alfa', 'beta'].

I will use the sublist in a with_items.

1 Answers

You can use the selectattr filter along with the in test for that.

Given:

- debug:
    var: some_list | selectattr('name', 'in', ['alfa', 'beta'])

This would yield:

ok: [localhost] => 
  some_list | selectattr('name', 'in', ['alfa', 'beta']):
  - dir: aaa
    name: alfa
  - dir: bbb
    name: beta
Related