# Setting a dictionary variable dynamically

**URL:** <https://forum.ansible.com/t/setting-a-dictionary-variable-dynamically/15368>\
**Category:** Ansible Project\
**Created:** [May 29, 2014, 6:59pm UTC](https://forum.ansible.com/t/setting-a-dictionary-variable-dynamically/15368 "2014-05-29T18:59:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Steve\_Fox](https://avatars.discourse-cdn.com/v4/letter/s/e47774/32.png) [@Steve\_Fox](https://forum.ansible.com/u/Steve_Fox)\
**Post date:** [May 29, 2014, 6:59pm UTC](https://forum.ansible.com/t/setting-a-dictionary-variable-dynamically/15368/1 "2014-05-29T18:59:15Z")

</div>

I’m struggling to find the best way to define a dictionary variable dynamically. My goal is to define a dictionary with product versions as keys and the latest revisions as values. That way I can define the path to the latest build for each product version.

It seems like a lookup plugin should be perfect, even though they’re required to return a list. I tried sending back the dictionary inside a list, but that fails with

“an unexpected type error occured. Error was sequence item 0: expected string, dict found”

I get this same error whether I use vars: or set\_fact with complex arguments.

I then took a different approach and converted my lookup plugin to a module which defines a specific fact. This worked, but unfortunately the fact is scoped to each host, so the module has to run repeatedly. Is there a better way?

---

<div class="post-metadata">

**Author:** ![Michael\_DeHaan1](https://avatars.discourse-cdn.com/v4/letter/m/5e9695/32.png) [@Michael\_DeHaan1](https://forum.ansible.com/u/Michael_DeHaan1)\
**Post date:** [May 31, 2014, 4:16pm UTC](https://forum.ansible.com/t/setting-a-dictionary-variable-dynamically/15368/2 "2014-05-31T16:16:55Z")

</div>

"I’m struggling to find the best way to define a dictionary variable dynamically. "

Sounds like you should just have a dictionary of values and use a variable to select an index into it, you don’t really want to define the dictionary dynamically but pick an element.

---

<div class="post-metadata">

**Author:** ![David\_Pujadas](https://avatars.discourse-cdn.com/v4/letter/d/e19b73/32.png) [@David\_Pujadas](https://forum.ansible.com/u/David_Pujadas)\
**Post date:** [November 3, 2015, 5:45pm UTC](https://forum.ansible.com/t/setting-a-dictionary-variable-dynamically/15368/3 "2015-11-03T17:45:05Z")

</div>

And how can I use a variable to select an index into a dictionary?

vars:  
ind: ‘ind1’  
dict:  
ind1:  
value: 1  
ind2:  
value: 2

I’d like to get something like {{ dict.{{ ind }} }} (which obviously fails …)
