Search code examples
ansibleansible-2.xansible-inventoryansible-factsansible-template

Identify the key value pair with duplicates in values of ansible dictionary


I have this dictionary:

Ip = {'a':['one','two','three'],'b':['one','five','six'],'c':['seven','eight','nine'],'d':['five']}

And I wish my output to be like this

Op = {'a':['one','two','three'],'b':['one','five','six'],'d':['five']}

Since it has some common values in the dictionary like 'one' or 'five', the duplicated value should be removed.


Solution

  • For example

        - set_fact:
            Op: "{{ Op|d({})|combine({item.key: Ip[item.key]}) }}"
          loop: "{{ Ip|dict2items }}"
          vars:
            _lists: "{{ Ip|dict2items|json_query('[].value') }}"
            _reduced: "{{ _lists|difference([item.value]) }}"
            _match: "{{ _reduced|map('intersect', item.value)|flatten }}"
          when: _match|length > 0
    

    gives

      Op:
        a:
        - one
        - two
        - three
        b:
        - one
        - five
        - six
        d:
        - five