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

如何在Ansible中将二维列表转换为字典列表?

在Ansible中将二维列表转换为字典列表的方法

要实现你需要的转换,核心是利用Ansible的过滤器链,结合zip和dict过滤器完成映射。以下是具体实现:

实现步骤

  1. 定义对应字典的键列表(如key1、key2);
  2. 通过map过滤器将二维列表的每个子列表与键列表按位置配对,再转成字典;
  3. 最终将结果转为列表,得到目标格式。

完整Playbook示例

- name: 二维列表转字典列表
  hosts: localhost
  vars:
    parent_list:
      - - "value1-1"
        - "value1-2"
      - - "value2-1"
        - "value2-2"
    # 字典的键,顺序要和子列表元素一一对应
    dict_keys: ["key1", "key2"]
  tasks:
    - name: 执行转换并输出结果
      debug:
        var: parent_list | map('zip', dict_keys) | map('dict') | list

过滤器解释

  • map('zip', dict_keys):把parent_list里的每个子列表,和dict_keys按位置配对,生成元组列表(比如第一个子列表会变成[("key1", "value1-1"), ("key2", "value1-2")]);
  • map('dict'):将每个元组列表转换为对应的字典;
  • list:确保最终输出是列表格式。

简化写法

如果键的数量固定且无需复用,可直接把键列表写在过滤器里,省去单独定义变量的步骤:

- name: 简化版转换
  debug:
    var: parent_list | map('zip', ["key1", "key2"]) | map('dict') | list

注意:子列表的元素数量必须和键列表长度一致,否则多余元素会被忽略,不足的位置会补None。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 10:22:06