Alexis.Rolland
Alexis.Rolland

Reputation: 6343

Build nested Python dictionary from flatten dictionary

I have the following flatten dictionary containing one entry for each item and each item contains a parent and children attribute.

{
    'a': {
        parent: None,
        children: ['b', 'c', 'd']
    },
    'b': {
        parent: 'a',
        children: ['e', 'f', 'g']
    },
    'c': {
        parent: 'a',
        children: []
    },
    'd': {
        parent: 'a',
        children: []
    },
    'e': {
        parent: 'b',
        children: []
    },
    'f': {
        parent: 'b',
        children: ['h']
    },
    'g': {
        parent: 'b',
        children: []
    },
    'h': {
        parent: 'f',
        children: []
    },
}

How can I turn it into a nested dictionary which looks like this?

{
    'a': {
        'b': {
            'e': {},
            'f': {
                'h':
            }
            'g': {}
        },
        'c': {},
        'd': {},
    }
}

Upvotes: 2

Views: 109

Answers (1)

Ajax1234
Ajax1234

Reputation: 71451

You can use recursion:

d = {'a': {'parent': None, 'children': ['b', 'c', 'd']}, 'b': {'parent': 'a', 'children': ['e', 'f', 'g']}, 'c': {'parent': 'a', 'children': []}, 'd': {'parent': 'a', 'children': []}, 'e': {'parent': 'b', 'children': []}, 'f': {'parent': 'b', 'children': ['h']}, 'g': {'parent': 'b', 'children': []}, 'h': {'parent': 'f', 'children': []}}
def group(start=None):
   return {a:group(a) for a, b in d.items() if b['parent'] == start}

import json
print(json.dumps(group(), indent=4))

Output:

{
  "a": {
     "b": {
        "e": {},
        "f": {
            "h": {}
        },
        "g": {}
     },
     "c": {},
     "d": {}
  }
}

Upvotes: 6

Related Questions