# Filter a list of dict

**URL:** <https://forum.ansible.com/t/filter-a-list-of-dict/6793>\
**Category:** Get Help\
**Tags:** jinja2\
**Created:** [June 26, 2024, 6:52pm UTC](https://forum.ansible.com/t/filter-a-list-of-dict/6793 "2024-06-26T18:52:32Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![DengelFred](https://avatars.discourse-cdn.com/v4/letter/d/87869e/32.png) [@DengelFred](https://forum.ansible.com/u/DengelFred)\
**Post date:** [June 26, 2024, 6:52pm UTC](https://forum.ansible.com/t/filter-a-list-of-dict/6793/1 "2024-06-26T18:52:32Z")

</div>

Hello!

I have a list of dicts with network definitions for an opnsense:

```auto
networks_test:
  - descr: UpLink
    iface: wan
    vlan_id: '7'

  - descr: MgmtNet
    iface: lan
    vlan_id: '40'
  - descr: HomeNet
    iface: opt1

```

In order to configure my vlans, I need a list of the keys ‘descr’ but only, if there is a ‘vlan\_id’ defined in the same dictionary.

I can create the list of ‘descr’:

```auto
- name: get list of VLANs
  ansible.builtin.set_fact:
    vlan_config: {{ networks_test | map(attribute='descr') }}

```

But how can I filter for the existence of the ‘vlan\_id’ key?  
In my case, the result should be:

```auto
"vlan_config": ["Uplink", "MgmtNet"]}

```

Thanks a lot!

---

<div class="post-metadata">

**Author:** ![DengelFred](https://avatars.discourse-cdn.com/v4/letter/d/87869e/32.png) [@DengelFred](https://forum.ansible.com/u/DengelFred)\
**Post date:** [June 26, 2024, 7:04pm UTC](https://forum.ansible.com/t/filter-a-list-of-dict/6793/2 "2024-06-26T19:04:45Z")

</div>

Just written, the solution came to my mind:

```auto
    - name: get list of configured VLANs
      ansible.builtin.set_fact:
        vlan_config: "{{ networks_test | selectattr('vlan_id', 'defined') | map(attribute='descr') }}"

```

Sorry for the question!

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/ansible/original/1X/1882d9a01da5d8996a862359b0913cc568a39b84.svg) [@system](https://forum.ansible.com/u/system)\
**Post date:** [July 26, 2024, 7:05pm UTC](https://forum.ansible.com/t/filter-a-list-of-dict/6793/3 "2024-07-26T19:05:30Z")

</div>

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.
