如何遍历字典列表

如何遍历字典列表

本文介绍了如何遍历字典列表,并打印出 Ansible 中的每个键和值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an list of dictionary in Ansible config

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 将起作用,但我也想知道密钥

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

推荐答案

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

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

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

将打印:

"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(' ') }}"

这将给出:

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

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

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.

这篇关于如何遍历字典列表,并打印出 Ansible 中的每个键和值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 05:07