# How to "flatten" nested keys in a dictionary, when key structure varies?

**URL:** <https://forum.ansible.com/t/how-to-flatten-nested-keys-in-a-dictionary-when-key-structure-varies/23164>\
**Category:** Ansible Project\
**Created:** [December 2, 2016, 7:03pm UTC](https://forum.ansible.com/t/how-to-flatten-nested-keys-in-a-dictionary-when-key-structure-varies/23164 "2016-12-02T19:03:38Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mike\_Titus1](https://avatars.discourse-cdn.com/v4/letter/m/9fc29f/32.png) [@Mike\_Titus1](https://forum.ansible.com/u/Mike_Titus1)\
**Post date:** [December 2, 2016, 7:03pm UTC](https://forum.ansible.com/t/how-to-flatten-nested-keys-in-a-dictionary-when-key-structure-varies/23164/1 "2016-12-02T19:03:38Z")

</div>

Given this YAML:

> somevar:  
> alpha:  
> beta:  
> gamma:  
> foo1: bar1  
> foo2: bar2  
> red:  
> green:  
> blue:  
> baz1: quz1  
> baz2: quz2

I want to construct strings of the full key paths:

> somevar/alpha/beta/gamma  
> somevar/red/green/blue

Thanks.

---

<div class="post-metadata">

**Author:** ![sivel](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/sivel/32/1198_2.png) [@sivel](https://forum.ansible.com/u/sivel)\
**Post date:** [December 2, 2016, 7:39pm UTC](https://forum.ansible.com/t/how-to-flatten-nested-keys-in-a-dictionary-when-key-structure-varies/23164/2 "2016-12-02T19:39:45Z")

</div>

There is no built in way to do this, however with a new custom filter, maybe you can get it:

def dict\_path(my\_dict, path=None):  
if path is None:  
path =   
for k, v in my\_dict.iteritems():  
newpath = path + [k]  
if isinstance(v, dict):  
for u in dict\_path(v, newpath):  
yield u  
else:  
yield newpath, v

class FilterModule(object):  
def filters(self):  
return {  
‘dict\_path’: dict\_path  
}

And then a playbook that makes use of this:

---

<div class="post-metadata">

**Author:** ![Mike\_Titus1](https://avatars.discourse-cdn.com/v4/letter/m/9fc29f/32.png) [@Mike\_Titus1](https://forum.ansible.com/u/Mike_Titus1)\
**Post date:** [December 2, 2016, 11:52pm UTC](https://forum.ansible.com/t/how-to-flatten-nested-keys-in-a-dictionary-when-key-structure-varies/23164/3 "2016-12-02T23:52:09Z")

</div>

That worked perfectly – thanks so much!
