0

I have a 2 list:

a = ['user','user2','user','user2']
b = ['value1','value1','value2','value1']

Is it possible to merge both and add "_" in between them

Looking for result:

result = ['user_value1','user2_value1','user_value2','user2_value1']

length of both lists will be same.

tried below no luck:(based on link Combine two lists and alternating the result in Jinja?

{%- set a = ['user1','user2','user3','user4'] -%}
{%- set b = ['value1','value2','value3','value4'] -%}
{%- set combined = (a,b) -%}

{%- set lengths = [] %}
{%- for row in combined -%}{%- if lengths.append(row|length)-%}{%- endif -%}{%- endfor -%}
{%- set max_length = (lengths|sort)[-1] -%}
{%- set rows = [] -%}    

{%- for r in range(max_length) -%}
        {%- for a in combined -%}
               {%- if a[r] -%}{%- if rows.append(a[r]) -%}{%- endif -%}{%- endif -%}
    {%- endfor -%}
{%- endfor -%}

{{ rows }}

thank you!

Tan512
  • 15
  • 6
  • ok, Converting 2 lists to dict, by in my case there are chances of first list having same set of values" like: a = ['user','user','user1','user1'], what to do in that case – Tan512 Jun 12 '20 at 08:17

2 Answers2

0

Try this:

- set_fact:
    some_list: "{{ (some_list | default([])) + [item | join('_')] }}"
  loop: "{{ a | zip(b) | list }}"

- debug: 
    msg: "{{ some_list | to_json }}"

Debug output:

TASK [debug] *******************************************************************************************************************************************************************************
ok: [localhost] => 
  msg: '["user1_value1", "user2_value2", "user3_value3", "user4_value4"]'
Moon
  • 2,837
  • 1
  • 20
  • 34
  • ok, Converting 2 lists to dict, by in my case there are chances of first list having same set of values" like: a = ['user','user','user1','user1'], what to do in that case – Tan512 Jun 12 '20 at 08:16
  • Should output the values as per the lists and result on your latest edit. Try executing the code with input lists. – Moon Jun 12 '20 at 09:51
  • Good to know. Would be glad if you can accept the answer in that case. May help others too. – Moon Jun 12 '20 at 10:13
0

It's not necessary to loop the list. The filter map does the job as well

    - set_fact:
        result: "{{ a|zip(b)|map('join','_')|list }}"



Q: "Converting 2 lists to dict ... first list having same set of values ['user','user','user1','user1']. What to do in that case?"

A: Use dict filter. The equivalent keys will replace each other with the last value standing. For example

    - set_fact:
        result: "{{ dict(a|zip(b)) }}"
    - debug:
        var: result

give

    "result": {
        "user": "value2",
        "user2": "value1"
    }
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63