0

I have information about a (simplified example) hierarchical taxonomy,

A - AA - AAA
A - AA - AAB

A - AB

B

I have data for it as a list of dicts in the following format:

[
{"name": "A",
"id": 10,
"path": ["A"]},

{"name": "AA",
"id": 7,
"path": ["A", "AA"]}

...

]

(the id is random)

I am trying to show it in a dash treeview widget based on AntD. It requires me to convert it to the following format:

[{"title": "A", "key": 10, "children": 
    [{"title": "AA", "key": 11, "children":
        [{...}] , 
    {"title": "AB", "key": 12},
    ...]},
{"title": "B", "key": 18}]

In other words, it's a recursive list of dicts, where there is a key called "children", which is another list of dicts taking on the same format.

I know I need to write a recursive function, but it's proving very tricky for me.

1 Answer 1

1

You could keep track of the nodes with a dictionary keyed by "title". Then for each element in a path, navigate through the tree, each time inserting into "children" when it is the first time that element is encountered:

def maketree(data):
    bytitle = {
        d["name"]: { "title": d["name"], "key": d["id"] }
        for d in data
    }
    
    root = { "children": [] }
    done = set()
    for node in data:
        current = root
        for title in node["path"]:
            if title not in done:
                done.add(title)
                if "children" not in current:
                    current["children"] = []
                current["children"].append(bytitle[title])
            current = bytitle[title]
    return root["children"]

// Example input and conversion
data = [
    {"name": "A",   "id": 10, "path": ["A"]},
    {"name": "AA",  "id": 7,  "path": ["A", "AA"]},
    {"name": "AAA", "id": 14, "path": ["A", "AA", "AAA"]},
    {"name": "AAB", "id": 12, "path": ["A", "AA", "AAB"]},
    {"name": "AB",  "id": 1,  "path": ["A", "AB"]},
    {"name": "B",   "id": 5,  "path": ["B"]},
]
tree = maketree(data)
print(tree)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.