Search code examples
dictionaryansiblekey-value

Remove items from a dictionary if condition is met


I have a dictionary dict1 from which I want to remove all items where b is null, that means not just the property b, but the whole dictionary.

- hosts: localhost
  gather_facts: false

  vars:
    dict1: [{a:1,b:2,c:3},{a:1,b:"null",c:3},{a:1,b:2,c:3}]

  tasks: 
  - set_fact:
      dict2: "{{item | reject(item.b, 'eq', 'null')}}"
    loop: "{{dict1}}"

The output should look like this:

dict2: [{a:1,b:2,c:3},{a:1,b:2,c:3}]

Note: there can be N items in the dictionary and/or N key-value pairs in the same dictionary. Also, there can be N number of b's in the dictionary that have null values, so it has to remove of all them.


Solution

  • You can use the selectattr filter to filter a list of dictionaries.

    Given the task:

    - debug:
        var: dict1 | selectattr('b', '!=', 'null')
    

    This would yield:

    dict1 | selectattr('b', '!=', 'null'):
      - a: 1
        b: 2
        c: 3
      - a: 1
        b: 2
        c: 3