How to remove a single key from an Ansible dictionary?

- set_fact:
    dict:
      a: 1
      b: 2
      c: 3
    dict2: {}

- set_fact:
    dict2: "{{dict2 |combine({item.key: item.value})}}"
  when: "{{item.key not in ['a']}}"
  with_dict: "{{dict}}"

- debug: var=dict2

or create a filter plugin and use it.


Here's an approach inspired by an article by John Mazzitelli that can be used inline without additional set_fact tasks, etc.:

Task:

tasks:
- debug: var=dict2
  vars:
    dict:
      a: 1
      b: 2
      c: 3
    # It is important that there be NO WHITESPACE outside of `{% ... %}` and `{{ ... }}`
    # or else the var will be converted to a string.  The copy() step optionally prevents
    # modifying the original. If you don't care, then: "{% set removed=dict.pop('a') %}{{dict}}"
    dict2: "{% set copy=dict.copy() %}{% set removed=copy.pop('a') %}{{ copy }}"

Outputs:

TASK [debug] ***********
ok: [localhost] => {
    "dict2": {
        "b": 2,
        "c": 3
    }
}

  - debug: var=dict2
    vars:
      dict:
        a: 1
        b: 2
        c: 3
      dict2: '{{ dict | dict2items | rejectattr("key", "eq", "a") | list | items2dict }}'
      #dict2: '{{ dict | dict2items | rejectattr("key", "match", "^(a|b)$") | list | items2dict }}'

Output:

ok: [localhost] => {
    "dict2": {
        "b": 2,
        "c": 3
    }
}