# Merging a list of dicts with another list of dicts

**URL:** <https://forum.ansible.com/t/merging-a-list-of-dicts-with-another-list-of-dicts/31057>\
**Category:** Ansible Project\
**Created:** [August 16, 2019, 8:42am UTC](https://forum.ansible.com/t/merging-a-list-of-dicts-with-another-list-of-dicts/31057 "2019-08-16T08:42:19Z")\
**Posts on this page:** 2\
**Page:** 1

<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:** [August 16, 2019, 8:42am UTC](https://forum.ansible.com/t/merging-a-list-of-dicts-with-another-list-of-dicts/31057/1 "2019-08-16T08:42:19Z")

</div>

Hi

I have a role for managing user accounts, which accepts a list of dicts to configure those, for example:

default\_users:

- name: bob  
comment: Bob Morton  
state: present
- name: dick  
comment: Dick Jones  
state: present
- name: alex  
comment: Alex Murphy  
state: present

Some systems need additional accounts, for instance:

customer\_users:

- name: anne  
comment: Anne Lewis  
state: present

This is easily done with the union filter:

“{{ default\_users | union(custom\_users) }}”

BUT, I would like users in the second list to override the ones in the first list, so that you change existing users. So for instance I would like to merge this in:

custom\_users:

- name: alex  
comment: Alex Murphy (locked for reason X)  
password\_lock: yes

So that the resulting list would look like this:

- name: bob  
comment: Bob Morton  
state: present
- name: dick  
comment: Dick Jones  
state: present
- name: alex  
comment: Alex Murphy (locked for reason X)  
password\_lock: yes  
state: present

So the lists of dicts need to be merged, and overwritten if the ‘name’ attribute is the same (if I express myself correctly).

union does not work here, and combine only works for individual dicts, not lists of dicts.

Before I set off to create my own filter - is there a way this could still be achieved using native ansible/jinja filters?

Thx

---

<div class="post-metadata">

**Author:** ![PhilEv](https://avatars.discourse-cdn.com/v4/letter/p/ee59a6/32.png) [@PhilEv](https://forum.ansible.com/u/PhilEv)\
**Post date:** [August 19, 2019, 12:50pm UTC](https://forum.ansible.com/t/merging-a-list-of-dicts-with-another-list-of-dicts/31057/2 "2019-08-19T12:50:32Z")

</div>

You might get what you need with the combine filter - not tested  
see [https://www.jeffgeerling.com/blog/2017/changing-deeply-nested-dict-variable-ansible-playbook](https://www.jeffgeerling.com/blog/2017/changing-deeply-nested-dict-variable-ansible-playbook) as an example

HTH

Phil
