using when inside and outside a loop

I want to do something like this below:

`

  • name: Create Simple list from Connection Dict
    set_fact:
    connections: “{{ connections | default() + [ {
    ‘switchid’: item.id,
    ‘connectionid’: item.connections[0].id
    } ] }}”
    when: item.connections #only want to create facts if connections exist
    loop: “{{ connections_result.json.0.switchPorts | flatten }}”
    when: connections_result is defined #depending on the host,connection_result.json may not be defined so need to check
    `

When I run the playbook, I get the following warning at the top

[WARNING]: While constructing a mapping from /home/xxx/xxxxx.yml, line 245, column 5, found a duplicate dict key (when). Using last defined value only.

Is there a way to get both when to work?

No. It's not possible. Instead, default to an empty list if the variable does
not exist. For example

   - name: Create Simple list from Connection Dict
     set_fact:
       connections: "{{ connections | default() + [ {
         'switchid': item.id,
         'connectionid': item.connections[0].id
         } ] }}"
     when: item.connections
     loop: "{{ connections_result.json.0.switchPorts|
               default()|
               flatten }}"

HTH,

  -vlado