On Wed, 22 Jan 2020 21:49:43 +0100
Vladimir Botka <[email protected]> wrote:

> The task below does the job
> 
>     - set_fact:
>         result_list: "{{ result_list|
>                          default([]) + [
>                          dict(keys|
>                               zip(keys|
>                                   map('extract', item)|
>                                   list))] }}"
>       vars:
>         keys: "{{ ['key1', 'key3', 'key4']|
>                   intersect(item.keys()|list) }}"
>       loop: "{{ list|
>                 selectattr('key3', 'regex', '^.*k.*$')|
>                 list }}"

Custom filter shall improve the efficiency. For example a filter to select a
list of keys from a dictionary

  $ cat filter_plugins/dict_utils.py
  def dict_select_list(d, l):
      d2 = {}
      for k in l:
          d2[k] = d[k]
      return d2

  class FilterModule(object):

      def filters(self):
          return {
              'dict_select_list' : dict_select_list
              }

The task below gives the same result

    - set_fact:
        result_list: "{{ result_list|
                         default([]) + [
                         item|dict_select_list(keys)] }}"
      vars:
        keys: "{{ ['key1', 'key3', 'key4']|
                  intersect(item.keys()|list) }}"
      loop: "{{ list|
                selectattr('key3', 'regex', '^.*k.*$')|
                list }}"

HTH,

        -vlado

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20200122232542.33072142%40gmail.com.

Attachment: pgp8bCCTqLH0t.pgp
Description: OpenPGP digital signature

Reply via email to