3

I have a string that looks like this:

s="Name1:Value1,Name2:Value2,Name3:Value3"

And I need to convert it to a dictionary like this:

dict = {
    "Name1": "Value1",
    "Name2": "Value2",
    "Name3": "Value3"
}

Which module or filter I should use?

Hristo Eftimov
  • 13,845
  • 13
  • 50
  • 77
AIG
  • 29
  • 1
  • 3

2 Answers2

0

Not very clean but you could try that:

---
- hosts: localhost
  vars:
    - s: "Name1:Value1,Name2:Value2,Name3:Value3"
    - tuples: "[{% for sub in s.split(',') %}{{sub.split(':')}},{% endfor %}]"
  tasks:
    - debug:
        msg: "{{ dict(tuples) }}"

Which gives:

TASK [debug] ************************************
ok: [localhost] => {
    "msg": {
        "Name1": "Value1",
        "Name2": "Value2",
        "Name3": "Value3"
    }
}
rolf82
  • 1,531
  • 1
  • 5
  • 15
-1
set_fact:
    dict: "{{ dict|default({}) | combine ( { item.split(':')[0] : item.split(':')[1] } ) }}" 
  with_items: 
    - "{{ a.split(',') }}"
AIG
  • 29
  • 1
  • 3
  • 1
    While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run. – Mustafa Apr 22 '20 at 02:13
  • This gives an error: |combine expects dictionaries, got at 0x7f9918d83668> – th3penguinwhisperer May 06 '20 at 14:03
  • Nevermind :( I made a booboo. Make sure to replace both 'dict' variable names with your name otherwise you get the error I mentioned. – th3penguinwhisperer May 06 '20 at 14:14