【问题标题】:How to loop through a list of dictionary, and print out every key and value pair in Ansible如何遍历字典列表,并打印出 Ansible 中的每个键值对
【发布时间】:2016-09-14 18:32:42
【问题描述】:

我在 Ansible 配置中有一个字典列表

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

我写代码

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

我想打印出来

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

我如何遍历这本字典并获取键值对?因为它不知道什么是关键。如果我更改为 {{ item.name }},ansible 将起作用,但我也想知道 key

【问题讨论】:

  • 通常对于这样的事情,我会定义一个类,然后根据您想要的可读性来利用__repr____str__,因为在您的示例中msg 看起来很容易解析,我会利用 repr
  • 谢谢你,@Fallenreaper。我不擅长python。你能解释更多吗? reprstr 是什么?
  • myList 后面有一个错字——冒号丢失。

标签: python ansible


【解决方案1】:

如果你想遍历列表并分别解析每个项目:

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

将打印:

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

如果您想将所有内容合并为一行,请使用:

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

这将给出:

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

请记住,字典在 Python 中没有排序,因此您通常不能期望您的项目与 yaml 文件中的顺序相同。在我的示例中,它们在 dictsort 过滤器之后按键名排序。

【讨论】:

  • 我可以保持字典顺序吗?
  • @Walter 恐怕不行。
  • @KonstantinSuvorov 如果列表有第三个“顺序”字段,您可以使用它对字典进行排序,然后确保输出中的顺序吗?
  • @dan_linder 不确定您的意思。如果你有一个清单——它已经被订购了。如果你有一个字典——它是未排序的。
  • @KonstantinSuvorov - 谢谢,我忽略了这一点。
【解决方案2】:

这是您的文字: 我的列表 - 姓名:鲍勃 年龄:25 - 姓名:爱丽丝 年龄:18 地址:美国

答案如下:

text='''我的列表 - 姓名:鲍勃 年龄:25 - 姓名:爱丽丝 年龄:18 地址:美国'''

>>> final_text=''

对于 text.split('\n') 中的行: line1=line.replace('','').replace('-','') 如果“myList”不在第 1 行: final_text+=line1+' '

final_text '姓名:鲍勃年龄:25 姓名:爱丽丝年龄:18 地址:美国 '

【讨论】:

  • 我能有ansible语法解决方案吗?
【解决方案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)

然后你可以有你创建的对象列表。我在这里使用一些示例数据来创建字典列表。

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)

结束打印:name:Hello World age:23 address:Test address name:Hello World age:23 address:Test address name:Hello World age:23 address:Test address

我打算做 REPR,但它的用法有点不同,我认为这可能更适合您的需求。

如果你想保持简单,你可以这样做:

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

【讨论】:

  • 所以在这种情况下,我应该创建一个单独的 python 文件来处理这个问题,如果没有额外的自定义模块,Ansible 就无法做到这一点。我说的对吗?
  • 添加了另一种方法,只有 2 个小循环
猜你喜欢
  • 2018-10-05
  • 2020-01-04
  • 1970-01-01
  • 2016-10-10
  • 2018-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-27
相关资源
最近更新 更多