list:
- key1:
- 'abc'
- 'def'
key2: 'ghi'
key3: 'jkl'
- key1:
- 'mno' - 'pqr'
key3: 'stu'
key4: 'dfg'
- key1:
- 'vwx'
- 'yza'
key3: 'okl'
key4: 'azel'
result_list:
- key1:
- 'abc'
- 'def'
key3: 'jkl'
- key1:
- 'vwx'
- 'yza'
key3: 'okl'
key4: 'azel'
- name: Filtering a complex list of dictionaries into another list of dictionaries
vars:
"list": [
{
"key1": [
"abc",
"def"
],
"key2": "ghi",
"key3": "jkl"
},
{
"key1": [
"mno",
"pqr"
],
"key3": "stu",
"key4": "dfg"
},
{
"key1": [
"vwx",
"yza"
],
"key3": "okl",
"key4": "azel"
}
]
set_fact:
result_list: "{{ result_list|default([]) + [ {'key3': item.key3, 'key4': item.key4|default('')} ] }}"
loop: "{{ list }}"
when: item.key3 | regex_search('(^.*k.*$)')
TASK [yang : Filtering a complex list of dictionaries into another list of dictionaries] *********************************************************************
task path: test.yml:133
<172.16.136.116> attempting to start connection
<172.16.136.116> using connection plugin network_cli
<172.16.136.116> found existing local domain socket, using it!
<172.16.136.116> updating play_context for connection
<172.16.136.116>
<172.16.136.116> local domain socket path is .ansible/pc/521e859c25
ok: [TEST] => (item={'key1': ['abc', 'def'], 'key2': 'ghi', 'key3': 'jkl'}) => {
"ansible_facts": {
"result_list": [
{
"key3": "jkl",
"key4": ""
}
]
},
"ansible_loop_var": "item",
"changed": false,
"item": {
"key1": [
"abc",
"def"
],
"key2": "ghi",
"key3": "jkl"
}
}
skipping: [TEST] => (item={'key1': ['mno', 'pqr'], 'key3': 'stu', 'key4': 'dfg'}) => {
"ansible_loop_var": "item",
"changed": false,
"item": {
"key1": [
"mno",
"pqr"
],
"key3": "stu",
"key4": "dfg"
},
"skip_reason": "Conditional result was False"
}
ok: [TEST] => (item={'key1': ['vwx', 'yza'], 'key3': 'okl', 'key4': 'azel'}) => {
"ansible_facts": {
"result_list": [
{
"key3": "jkl",
"key4": ""
},
{
"key3": "okl",
"key4": "azel"
}
]
},
"ansible_loop_var": "item",
"changed": false,
"item": {
"key1": [
"vwx",
"yza"
],
"key3": "okl",
"key4": "azel"
}
}
...
vars:
keys: "{{ ['key1', 'key3', 'key4', 'key5', 'key6']|
intersect(item.keys()|list) }}"
loop: "{{ list|
selectattr('key3', 'regex', 'regex1|regex2|regex3')|
list }}"