1

For an anytree Node, how can I get all the attributes and their values?

For example, if I do:

>>> from anytree import Node
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root, foo="10", bar="ggg")

how can I get something like [("foo", "10"), ("bar", "ggg")]?

I can think of a route via the following:

>>> s1=Node("dummy", parent=root)
>>> set(dir(s0))-set(dir(s1))
{'foo', 'bar'}

but I hope there is a more concise way.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
norio
  • 3,652
  • 3
  • 25
  • 33
  • The documentation you link to includes a list of all of a `Node`'s methods, which doesn't include what you're asking for. As you already know, you can use `dir` to get all of the attribute names (then e.g. `getattr` to access their values) but that will include some you don't consider relevant. – jonrsharpe Jan 03 '22 at 12:49

1 Answers1

1

This is working in your case:

s0.__dict__.items()

However, beware that this method relies on the inner implementation of anytree (and it's always a bad idea to rely on a specific implementation). Also, the __dict__ attribute contains also the name, parent and (optionally) children (and you might want to get rid of these).

[(k, v) for k, v in s0.__dict__.items() if k not in ('name', 'parent', 'children')]
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50