# Item exists in list of dicts?

**URL:** <https://forum.ansible.com/t/item-exists-in-list-of-dicts/18918>\
**Category:** Ansible Project\
**Created:** [August 2, 2015, 8:10am UTC](https://forum.ansible.com/t/item-exists-in-list-of-dicts/18918 "2015-08-02T08:10:30Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Nico\_K](https://avatars.discourse-cdn.com/v4/letter/n/46a35a/32.png) [@Nico\_K](https://forum.ansible.com/u/Nico_K)\
**Post date:** [August 2, 2015, 8:10am UTC](https://forum.ansible.com/t/item-exists-in-list-of-dicts/18918/1 "2015-08-02T08:10:30Z")

</div>

Hi,

I’ve been restructuring my variables and ended up with something along the lines of:

files:

- { src: ‘a’ }
- { src: ‘b’ }

and a role that does:

- name: x  
template:  
src: {{ item.src }}  
…  
mode: {{ item.mode|default(0755) }}  
owner: {{ item.owner|default(root) }}

This allows me to easily override the ownership/mode on a single file, yet have defaults for them if not specified, it also makes a step like this easily exchangeable with other roles (assuming you use the same variable structure there).  
Anyway, what’s problematic with such a layout is to determine whether a given file exists in a list of other files (for example for the sake of removing unmanaged files), think:

(Please bear in mind that I’m typing this from memory, so if I mixed up the syntax of a module, no need to point that out, just trying to illustrate my use-case)

- name: collect files…  
shell: blah  
register: found\_files

- name: remove unmanaged  
file:  
path: {{ item }}  
state: absent  
with\_items:

- found\_files  
when: item not in files

This is where it goes wrong, as files no longer is a flat list, but a list containing a dictionary; is there an easy way to say “when: item not in files.[\*].src”? Or do I have to start using with\_nested in this case (results in quite some overhead!!).

Thanks,  
Nico

---

<div class="post-metadata">

**Author:** ![Nico\_K](https://avatars.discourse-cdn.com/v4/letter/n/46a35a/32.png) [@Nico\_K](https://forum.ansible.com/u/Nico_K)\
**Post date:** [August 2, 2015, 4:52pm UTC](https://forum.ansible.com/t/item-exists-in-list-of-dicts/18918/2 "2015-08-02T16:52:53Z")

</div>

In case anyone cares, the way to do this is:

- name: x  
set\_fact:  
src\_from\_list: “{{ files|map(attribute=‘src’)|list }}”

- name: y  
debug: msg=‘{{ item }}’  
with\_items:

- “{{ src\_from\_list }}”

which then outputs the values of ‘src’ (that being ‘a’, and ‘b’)

Thanks,  
Nico
