BacklogZero®

Ansible in a Minute · Ansible Core ·

Use list to loop over dictionary keys

Short answer

Pipe dict.keys() through the list filter so a loop works on Python 3.

Subscribe for updates

Get an email whenever we publish new guides and blog posts. Unsubscribe anytime.

By subscribing you agree we may email you about Ansible in a Minute and related Level Up Labs updates. We store your address in the same lead sheet as our contact form.

Request

loop service_ports.keys() piped through list filter

Example

A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.

YAML
---
- name: Loop over dictionary keys with the list filter
  hosts: all
  gather_facts: false
  vars:
    service_ports:
      http: 80
      https: 443
  tasks:
    - name: Print each service port key
      ansible.builtin.debug:
        msg: "{{ item }}"
      loop: "{{ service_ports.keys() | list }}"

How it works

On Python 3, keys(), values(), and items() return a view. Ansible cannot turn that view string back into a list. The list filter makes the loop portable.

When to use it

  • Looping over keys or values of a dict var
  • Writing templates that run on Python 3 controllers

Requirements

  • Ansible: >=2.14

Validation

  • Syntax validated
  • Not execution-tested
  • Last verified 2026-09-15

Notes

Use dict.items() | list when you need key and value. Do not use iterkeys(), itervalues(), or iteritems(). Those methods do not exist in Python 3.

Reference

Built for every Ansible use case in every organization

BacklogZero can generate this kind of automation in your environment, just like it did here.

Get BacklogZero today

Related guides

Back to Ansible in a Minute

Use list to loop over dictionary keys · Level Up Labs