我想从两个列表中获取字典列表,并按唯一字段进行过滤。 例如:我需要创建键值对,使两个列表中的元素都是唯一的。
我正在尝试使用嵌套循环:
- name: "Create list"
gather_facts: false
hosts: all
vars:
var1:
- '1'
- '2'
- '3'
var2:
- 'a'
- 'b'
- 'c'
tasks:
- name: "Merge lists"
ansible.builtin.set_fact:
new_list: "{{ new_list | default([]) + [{'var1': (item[0] | string), 'var2': (item[1] | string)}] }}"
loop: "{{ var1 | product(var2) | list }}"
- name: "Print new_list"
ansible.builtin.debug:
msg: "{{ new_list }}"
结果如下:
[
{
"var1": "1",
"var2": "a"
},
{
"var1": "1",
"var2": "b"
},
{
"var1": "1",
"var2": "c"
},
{
"var1": "2",
"var2": "a"
},
{
"var1": "2",
"var2": "b"
},
{
"var1": "2",
"var2": "c"
},
{
"var1": "3",
"var2": "a"
},
{
"var1": "3",
"var2": "b"
},
{
"var1": "3",
"var2": "c"
}
]
我想要的结果:
[
{
"var1": "1",
"var2": "a"
},
{
"var1": "2",
"var2": "b"
},
{
"var1": "3",
"var2": "c"
}
]
我试图从this查询中找出示例,但那里的情况与我的不同。
根据您想要的输出,您可以简化问题,如以下演示手册所示:
---
- name: Manipulate lists
hosts: localhost
gather_facts: false
vars:
var1:
- 1
- 2
- 3
var2:
- a
- b
- c
new_list: >-
{{
dict(
var1 | map('string') | zip(var2 | map('string'))
)
| dict2items(key_name='var1', value_name='var2')
}}
tasks:
- name: Show calculated list
debug:
var: new_list
给出:
PLAY [Manipulate lists] *******************************************************************************************************************************************************************************************
TASK [Show calculated list] ***************************************************************************************************************************************************************************************
ok: [localhost] => {
"new_list": [
{
"var1": "1",
"var2": "a"
},
{
"var1": "2",
"var2": "b"
},
{
"var1": "3",
"var2": "c"
}
]
}
PLAY RECAP ********************************************************************************************************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0