How to loop through a list of dictionary, and print out every key and value pair in Ansible
<p>I have an list of dictionary in Ansible config</p>

<pre><code>myList
    - name: Bob
      age: 25
    - name: Alice
      age: 18
      address: USA
</code></pre>

<p>I write code as</p>

<pre><code>- name: loop through
  debug: msg ="{{item.key}}:{{item.value}}"
  with_items: "{{ myList }}"
</code></pre>

<p>I want to print out like</p>

<pre><code>msg: "name:Bob age:25 name:Alice age:18 address:USA"
</code></pre>

<p>How can I loop through this dictionary and get key and value pairs? Because it don't know what is the key. If I change as {{ item.name }}, ansible will work, but I also want to know key</p>

<pre><code>class Person(object):
  def __init__(self, name, age, address):
    self.name = name
    self.age = age
    self.address = address

  def __str__(self):
    # String Representation of your Data.
    return "name:%s age:%d address:%s" % (self.name, self.age, self.address)
</code></pre>

<p>then you can have a list of objects you created.  I am using some sample data here to create a list of dicts.</p>

<pre><code>dict={"name":"Hello World", "age":23, "address":"Test address"}
myList = [dict,dict,dict]
objList = []
for row in myList:
  objList.append(str(Person(**row)))

result = ' '.join(objList)
print(result)
</code></pre>

<p>It ends out printing: <strong>name:Hello World age:23 address:Test address name:Hello World age:23 address:Test address name:Hello World age:23 address:Test address</strong></p>

<p>I was going to do REPR but that is used a bit more differently, and i thought this might be better suited for your needs.</p>

<p>If you want to keep it really simple you can do this:</p>

<pre><code>dict={"name":"Hello World", "age":23, "address":"Test address"}
myList = [dict,dict,dict]
objList = []
for row in myList;
  tmp = []
  for k in row:
    tmp.append("%s:%s" % (k, row[k]))
  objList.append(" ".join(tmp))
print(" ".join(objList))
</code></pre>

python ansible