Emilio Garçia
Emilio Garçia

Reputation: 246

Filter list of dicts by dict key

I have a dict of lists:

{
    "foo": [
        "A", 
        "B", 
        "C"
    ], 
    "bar": [
    ], 
    "baz": [
        "D", 
        "E"
    ]
}

I would like to remove the dict element bar, so that only foo and baz remain. This does not even have to be dynamicly detecting empty lists, I know the element bar will be empty and I'll be happy to have a solution to remove it by name - or remove empty lists if that is easier.

I would like to do this with a filter, not in an Ansible loop. Any chance wihtout writing a custom filter? I have not found any built-in filter which appears like it could do this. reject and rejectattr work with lists of dicts, not with a dict containing lists.

Upvotes: 2

Views: 879

Answers (1)

yaegashi
yaegashi

Reputation: 1510

---
- hosts: all
  gather_facts: no
  vars:
    dict: { foo: [ A, B, C ], bar: [], baz: [ D, E ] }
    dict_filtered: |
      {%- set o={} %}
      {%- for k, v in dict.iteritems() %}
        {%- if v %}
          {%- if o.update({k: v}) %}
          {%- endif %}
        {%- endif %}
      {%- endfor %}
      {{ o }}
  tasks:
    - debug:
        var: dict_filtered

sample session:

$ ansible-playbook -i localhost, playbook.yml 

PLAY [all] ******************************************************************** 

TASK: [debug ] **************************************************************** 
ok: [localhost] => {
    "var": {
        "dict_filtered": {
            "baz": [
                "D", 
                "E"
            ], 
            "foo": [
                "A", 
                "B", 
                "C"
            ]
        }
    }
}

PLAY RECAP ******************************************************************** 
localhost                  : ok=1    changed=0    unreachable=0    failed=0   

Upvotes: 3

Related Questions