How to loop through a list of dictionary, and prin

2019-02-19 04:52发布

问题:

I have an list of dictionary in Ansible config

myList
    - name: Bob
      age: 25
    - name: Alice
      age: 18
      address: USA

I write code as

- name: loop through
  debug: msg ="{{item.key}}:{{item.value}}"
  with_items: "{{ myList }}"

I want to print out like

msg: "name:Bob age:25 name:Alice age:18 address:USA"

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

回答1:

If you want to loop through the list and parse every item separately:

- debug: msg="{{ item | dictsort | map('join',':') | join(' ') }}"
  with_items: "{{ myList }}"

Will print:

"msg": "age:25 name:Bob"
"msg": "address:USA age:18 name:Alice"

If you want to join everything into one line, use:

- debug: msg="{{ myList | map('dictsort') | sum(start=[]) | map('join',':') | join(' ') }}"

This will give:

"msg": "age:25 name:Bob address:USA age:18 name:Alice"

Keep in mind that dicts are not sorted in Python, so you generally can't expect your items to be in the same order as in yaml-file. In my example, they are sorted by key name after dictsort filter.



回答2:

Here is your text: myList - name: Bob age: 25 - name: Alice age: 18 address: USA

Here is the Answer:

text='''myList - name: Bob age: 25 - name: Alice age: 18 address: USA'''

>>> final_text=''

for line in text.split('\n'): line1=line.replace(' ','').replace('-','') if 'myList' not in line1: final_text+=line1+' '

final_text 'name:Bob age:25 name:Alice age:18 address:USA '



回答3:

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)

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

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)

It ends out printing: name:Hello World age:23 address:Test address name:Hello World age:23 address:Test address name:Hello World age:23 address:Test address

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.

If you want to keep it really simple you can do this:

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))