# Dynamic dictionary key

**URL:** <https://forum.ansible.com/t/dynamic-dictionary-key/34621>\
**Category:** Ansible Project\
**Created:** [February 15, 2021, 11:32am UTC](https://forum.ansible.com/t/dynamic-dictionary-key/34621 "2021-02-15T11:32:43Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rishare\_Rishare](https://avatars.discourse-cdn.com/v4/letter/r/8c91f0/32.png) [@Rishare\_Rishare](https://forum.ansible.com/u/Rishare_Rishare)\
**Post date:** [February 15, 2021, 11:32am UTC](https://forum.ansible.com/t/dynamic-dictionary-key/34621/1 "2021-02-15T11:32:43Z")

</div>

Hi,

I can’t find any easy way how to do something like this:

- set\_fact:  
“mydict[{{ myvar }}]”: “value”  
vars:  
myvar: “blabla”

However it does not work, because the variable name is not evaluated. The only way I found to do this is very ugly:

- set\_fact:  
mydict: “{{ mydict | combine({ myvar: ‘value’ }, recursive=true) }}”  
vars:  
myvar: “blabla”

That is very ugly and can get out of hand quickly when going into deeper nested dictionaries.

Any ideas how to make it “nicer”?

---

<div class="post-metadata">

**Author:** ![Dick\_Visser](https://avatars.discourse-cdn.com/v4/letter/d/d9b06d/32.png) [@Dick\_Visser](https://forum.ansible.com/u/Dick_Visser)\
**Post date:** [February 15, 2021, 12:24pm UTC](https://forum.ansible.com/t/dynamic-dictionary-key/34621/2 "2021-02-15T12:24:45Z")

</div>

Not really. I have some similar cases where I resort to defining a list and the using items2dict to come up with the structure that I need.

---

<div class="post-metadata">

**Author:** ![Nuno\_Jordao](https://avatars.discourse-cdn.com/v4/letter/n/a4c791/32.png) [@Nuno\_Jordao](https://forum.ansible.com/u/Nuno_Jordao)\
**Post date:** [February 15, 2021, 4:39pm UTC](https://forum.ansible.com/t/dynamic-dictionary-key/34621/3 "2021-02-15T16:39:55Z")

</div>

Hello,

I am not sure it helps in your case, but I had success in past generating complex structures with a json template and importing it into a variable:

set\_fact:  
data: “{{ lookup(‘template’, ‘templates/data.json.j2’) }}”

It’s much faster than doing combines and loops.

Nuno Jordão
