Liste des dicts à dict multiniveaux en fonction des informations de profondeur

9

J'ai quelques données, plus ou moins comme ceci:

[
{"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},
]

Je veux le transformer en un dict multiniveau basé sur le niveau de profondeur (clé "niveau"):

{
    "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": {}}}}}}
}

Tout ce que je peux trouver en ce moment, c'est ce petit morceau de code ... qui se casse évidemment après quelques éléments:

def list2multilevel(list):
    children = {}
    parent = list.pop(0)
    tag = parent.get("Tag")
    level = parent.get("Level")
    for child in list:
        ctag = child.get("Tag")
        clevel = child.get("Level")
        if clevel == level + 1:
            children.update(list2multilevel(list))
        elif clevel <= level:
            print(clevel, level)
            break
    return {tag: children}

À l'origine, il s'est assis vendredi et c'était censé être juste un petit exercice ...

MrPilipo
la source

Réponses:

6
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)

production:

{'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
  • Aucun levelne peut être plus grand que le +1niveau maximum apparu auparavant.

explication:

  • parents est un dictionnaire pour se souvenir du dernier élément de chaque niveau.
  • root est un point de départ (élément factice).
  • logique:
    • Commencez par le -1niveau qui indique le root.
    • Faites un article et enregistrez-le chez les parents children.
    • Mettre à jour le même élément dans le parentsdictionnaire.
    • Répéter.
    • Extraire root['children'].
Boseong Choi
la source
1

Autre solution utilisant la récursivité (mêmes restrictions qu'avec la réponse de Boseong Choi):

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},
]

def make_node(dic):
    node = dic.copy()
    node["children"] = {}
    tag = node.pop("tag")
    return tag, node

def add_child(parent, child, tag):
    assert child["level"] > parent["level"]
    if child["level"] == parent["level"] + 1:
        parent["children"][tag] = child
        return True
    for node in parent["children"].values():
        if add_child(node, child, tag):
            return True
    return False

def parse(lst):
    assert lst[0]["level"] == 0
    root_tag, root = make_node(lst[0])
    for item in lst[1:]:
        tag, node = make_node(item)
        add_child(root, node, tag)


print(parse(data))
bruno desthuilliers
la source
-1

Vous pouvez utiliser la récursivité:

from itertools import groupby as gb
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}]
def to_tree(d, s = 0):
  v = [list(b) for _, b in gb(d, key=lambda x:x['level'] == s)]
  if len(v) == 1:
     return {i['tag']:{'level':s, 'children':{}} for i in v[0]}
  return {v[i][0]['tag']:{'level':s, 'children':to_tree(v[i+1], s+1)} for i in range(0, len(v), 2)}

import json
print(json.dumps(to_tree(data), indent=4))

Production:

{
  "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": {}
                }
            }
         }
      }
   }
}
Ajax1234
la source
Pourquoi les downvotes?
Ajax1234