'Change Ansible key in a dict
I have a dictionary in Ansible.
my_dict:
key1 : value1
key2 : value2
key3 : value3
key4 : value4
I would like the final output to be
my_dict:
key1 : value1
key2 : value2
key33 : value3
key4 : value4
Is there a way to change the dictionary key from key3 to key33 ? Thanks
Solution 1:[1]
Q: "Is there a way to change the dictionary key from key3 to key33?"
A: No. There is not. A new dictionary must be created. For example
- hosts: localhost
vars:
my_dict:
key1 : value1
key2 : value2
key3 : value3
key4 : value4
tasks:
- set_fact:
my_dict2: "{{ my_dict2|default({})|
combine({my_dict_trans[item.key]|
default(item.key): item.value}) }}"
loop: "{{ my_dict|dict2items }}"
vars:
my_dict_trans:
key3: key33
- debug:
var: my_dict2
gives
my_dict2:
key1: value1
key2: value2
key33: value3
key4: value4
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |