Ansible如何合并两个字典列表实现类字典方式访问元素
问题核心原因
你当前定义的lista1.fruits、lista2.vegetables都是列表类型,列表无法直接通过属性名访问内部元素的字段,必须通过下标或者遍历才能取值,这是你需要用regex_search迂回匹配的根本原因。
解决思路
把列表结构转换为以食物名称为键的字典结构,即可实现点号直接访问属性的需求,不需要额外正则匹配。
可直接运行的完整Playbook
--- - name: 实现类字典方式访问食物属性 hosts: localhost vars: lista1: fruits: - name: tomato taste: tomato-like - name: lemon taste: sour lista2: vegetables: - name: carrot taste: sweet tasks: # 把列表转为字典,key为食物name,value为完整的食物属性对象 - name: 重构列表为字典结构 set_fact: lista1: "{{ lista1 | combine({'fruits': dict(lista1.fruits | map(attribute='name') | zip(lista1.fruits))}) }}" lista2: "{{ lista2 | combine({'vegetables': dict(lista2.vegetables | map(attribute='name') | zip(lista2.vegetables))}) }}" # 测试直接点号访问 - name: 测试访问tomato属性 debug: msg: "Fruit {{ lista1.fruits.tomato.name }} has taste {{ lista1.fruits.tomato.taste }}" - name: 测试访问carrot属性 debug: msg: "Vegetable {{ lista2.vegetables.carrot.name }} has taste {{ lista2.vegetables.carrot.taste }}"
效果说明
重构后你可以按任意需求直接取值:
- 访问柠檬的味道:
{{ lista1.fruits.lemon.taste }} - 访问胡萝卜的名称:
{{ lista2.vegetables.carrot.name }}
完全不需要遍历或者正则匹配,符合你要的类字典访问要求。
内容的提问来源于stack exchange,提问作者Irka Irenka
相关产品推荐
相关产品推荐

