You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Ansible中product生成的列表嵌套转为字典列表?

解决Ansible中product过滤器结果转字典列表的问题

你可以通过两种方式实现需求:

方法1:用product配合map过滤器转换

利用product生成笛卡尔积后,通过map过滤器将每个子列表映射为指定结构的字典,需要用到community.general.dict插件(未安装的话可执行ansible-galaxy collection install community.general):

- name: experimenting
  hosts: localhost
  tasks:
  - name: Define some facts
    set_fact:
      people:
      - name: "Fred"
      - name: "John"
      animals:
      - name: "cat"

  - debug:
      msg: "{{ animals | product(people) | map('community.general.dict', keys=['animal', 'person']) | list }}"

方法2:直接用Jinja2列表推导式(贴近LINQ Select的写法)

Jinja2支持类似LINQ的列表推导,直接遍历笛卡尔积并生成目标字典,无需依赖额外集合:

- name: experimenting
  hosts: localhost
  tasks:
  - name: Define some facts
    set_fact:
      people:
      - name: "Fred"
      - name: "John"
      animals:
      - name: "cat"

  - debug:
      msg: "{{ [ {'animal': animal, 'person': person} for animal in animals for person in people ] }}"

效果说明

两种方法都会输出你需要的字典列表格式:

ok: [localhost] => {
    "msg": [
        {
            "animal": {
                "name": "cat"
            },
            "person": {
                "name": "Fred"
            }
        },
        {
            "animal": {
                "name": "cat"
            },
            "person": {
                "name": "John"
            }
        }
    ]
}

内容的提问来源于stack exchange,提问作者Alex Dresko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 10:32:47