0

If I have this tree:

# mytree.py
import anytree as at
import anytree.importer


data = {
    "a": "root",
    "children": [
        {
            "a": "sub0",
            "b": 3,
            "children": [{"a": "sub0A", "b": 9}, {"a": "sub0B", "b": 1}],
        },
        {"a": "sub1", "b": 5},
    ],
}
root = at.importer.DictImporter().import_(data)
python3 -i mytree.py
print(at.RenderTree(root, style=at.render.ContStyle()))
AnyNode(a='root')
├── AnyNode(a='sub0', b=3)
│   ├── AnyNode(a='sub0A', b=9)
│   └── AnyNode(a='sub0B', b=1)
└── AnyNode(a='sub1', b=5)

How can I build this other tree (without altering the original)?

AnyNode(a='root')
├── AnyNode(a='sub0', c="small")
│   ├── AnyNode(a='sub0A', c="large")
│   └── AnyNode(a='sub0B', c="small")
└── AnyNode(a='sub1', c="small")

It has the same structure ("shape"), but each node doesn't have a b attribute and has a cattribute that's "small" if the original node's b was smaller than 6, and "large" if it was >=6.

I've tried to iterate over the original tree with something like

for on_this_level in at.LevelOrderGroupIter(root)

but couldn't make it work.

Daniel Diniz
  • 175
  • 8

1 Answers1

0

Create another tree as copy, then - change its root descendants directly as shown below:

import copy

new_root = copy.deepcopy(root)
for dsc in new_root.descendants:
    dsc.c = 'large' if dsc.b >=6 else 'small'
    del dsc.b
    
print(at.RenderTree(new_root, style=at.render.ContStyle()))

AnyNode(a='root')
├── AnyNode(a='sub0', c='small')
│   ├── AnyNode(a='sub0A', c='large')
│   └── AnyNode(a='sub0B', c='small')
└── AnyNode(a='sub1', c='small')
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • Hm, I used a dict just to come up with a simple example tree, my "real use case" tree was built with a parser. So I must find a way that uses the tree itself; unless converting the tree to a dict, altering the dict, and then importing it to a new tree is a solution... (but there's probably a better way, I imagine) – Daniel Diniz Jan 28 '23 at 21:56
  • 1
    @DanielDiniz, if that's all, that's not a problem - see my update – RomanPerekhrest Jan 28 '23 at 22:06