Skip to content

Instantly share code, notes, and snippets.

@WLPhoenix
Last active August 29, 2015 14:09
Show Gist options
  • Save WLPhoenix/bd00b7d8afd690a20c59 to your computer and use it in GitHub Desktop.
Save WLPhoenix/bd00b7d8afd690a20c59 to your computer and use it in GitHub Desktop.
Python dict deepen
def deepen(shallow_obj):
"""Recursively deepens a dictionary based on keys"""
shallow_copy = copy.copy(shallow_obj)
deep_obj = {}
for key in shallow_copy:
if isinstance(shallow_copy[key], dict):
shallow_copy[key] = deepen(shallow_copy[key])
t = deep_obj
parts = key.split('.')
n_key = parts.pop()
while parts:
part, parts = parts[0], parts[1:]
t[part] = t.get(part, {})
t = t[part]
t[n_key] = shallow_copy[key]
return deep_obj
@WLPhoenix
Copy link
Author

Takes properties in

{
    "a.b.c": "taco",
    "a.d": "burrito"
}

and converts it to

{
    "a": {
        "b": {
            "c": "taco"
        },
        "d": "burrito"
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment