List of dicts to multilevel dict based on depth info

data = [
    {"tag": "A", "level": 0},
    {"tag": "B", "level": 1},
    {"tag": "D", "level": 2},
    {"tag": "F", "level": 3},
    {"tag": "G", "level": 4},
    {"tag": "E", "level": 2},
    {"tag": "H", "level": 3},
    {"tag": "I", "level": 3},
    {"tag": "C", "level": 1},
    {"tag": "J", "level": 2},
]

root = {'level': -1, 'children': {}}
parents = {-1: root}
for datum in data:
    level = datum['level']
    parents[level] = parents[level - 1]['children'][datum['tag']] = {
        'level': datum['level'],
        'children': {},
    }
result = root['children']
print(result)

output:

{'A': {'level': 0, 'children': {'B': {'level': 1, 'children': {'D': {'level': 2, 'children': {'F': {'level': 3, 'children': {'G': {'level': 4, 'children': {}}}}}}, 'E': {'level': 2, 'children': {'H': {'level': 3, 'children': {}}, 'I': {'level': 3, 'children': {}}}}}}, 'C': {'level': 1, 'children': {'J': {'level': 2, 'children': {}}}}}}}

restriction:

  • level >= 0
  • Any level cannot be bigger than +1 of max level appeared before.

explanation:

  • parents is a dictionary to remember last element for each level.
  • root is a starting point(dummy element).
  • logic:
    • Start with -1 level which indicates the root.
    • Make an item and register it into parent's children.
    • Update same item to parents dictionary.
    • Repeat.
    • Extract root['children'].