# find element with dictionary in Ansible and return value

**URL:** <https://forum.ansible.com/t/find-element-with-dictionary-in-ansible-and-return-value/36875>\
**Category:** Ansible Project\
**Created:** [July 20, 2022, 10:32am UTC](https://forum.ansible.com/t/find-element-with-dictionary-in-ansible-and-return-value/36875 "2022-07-20T10:32:40Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![maulik\_patel](https://avatars.discourse-cdn.com/v4/letter/m/ec9cab/32.png) [@maulik\_patel](https://forum.ansible.com/u/maulik_patel)\
**Post date:** [July 20, 2022, 10:32am UTC](https://forum.ansible.com/t/find-element-with-dictionary-in-ansible-and-return-value/36875/1 "2022-07-20T10:32:40Z")

</div>

hi ,

i’m trying to value of one yaml file1 with another file2 which has list of dict and if element if file1 matched with key/value of file2 then need to use value of file1 need to use as a key of file2 and return value of it…

not sure how we can leverage “when” condition or might any other way around it…

**file1.yaml:**

_site: CL1_

**file2.yaml:**

_site\_int:_

---

<div class="post-metadata">

**Author:** ![Akasurde](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/akasurde/32/230_2.png) [@Akasurde](https://forum.ansible.com/u/Akasurde)\
**Post date:** [July 21, 2022, 2:09pm UTC](https://forum.ansible.com/t/find-element-with-dictionary-in-ansible-and-return-value/36875/2 "2022-07-21T14:09:53Z")

</div>

The last task should be -

```auto

- debug:
msg: "{{ sites[site] }}"
when: "site in sites.keys()"
```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/ansible/original/1X/1882d9a01da5d8996a862359b0913cc568a39b84.svg) [@system](https://forum.ansible.com/u/system)\
**Post date:** [July 21, 2022, 2:24pm UTC](https://forum.ansible.com/t/find-element-with-dictionary-in-ansible-and-return-value/36875/3 "2022-07-21T14:24:43Z")

</div>

First you conflate site as both a variable and a string, showing both  
examples below to make the distinction clear.

You don't need key/keys() nor quotes if 'site' is a variable

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;when: site in sites

You seem to use site as both var and string, if site is a string, you  
need quotes

&nbsp;&nbsp;&nbsp;&nbsp;when: "'site' in sites"

also you can do this

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;msg: "{{ sites.get(site)}}" if variable or msg: "{{  
sites.get('site')}}" if string

Avoids error and shows 'none' if missing.
