GetListOfKeys from a tree

Dear,

How do you get the name of variables in a tree using GetListOfKeys()?

file = ROOT.TFile(Path+rootfile,“read”)
#how to switch to the tree?
rootkeys = file.GetListOfKeys()
for key in rootkeys:
#here I want to print the name of variables inside the ttree
print key.GetName()

Many thanks!

Maybe @etejedor has another method, but here is a simple way:

>>> file = ROOT.TFile('hsimple.root')
>>> ntuple = gROOT.FindObject('ntuple')
>>> ntuple.Print()
******************************************************************************
*Tree    :ntuple    : Demo ntuple                                            *
*Entries :    25000 : Total =          504554 bytes  File  Size =     401797 *
*        :          : Tree compression factor =   1.25                       *
******************************************************************************
*Br    0 :px        : Float_t                                                *
*Entries :    25000 : Total  Size=     100830 bytes  File Size  =      93378 *
*Baskets :        5 : Basket Size=      32000 bytes  Compression=   1.07     *
*............................................................................*
*Br    1 :py        : Float_t                                                *
*Entries :    25000 : Total  Size=     100830 bytes  File Size  =      93373 *
*Baskets :        5 : Basket Size=      32000 bytes  Compression=   1.07     *
*............................................................................*
*Br    2 :pz        : Float_t                                                *
*Entries :    25000 : Total  Size=     100830 bytes  File Size  =      91694 *
*Baskets :        5 : Basket Size=      32000 bytes  Compression=   1.09     *
*............................................................................*
*Br    3 :random    : Float_t                                                *
*Entries :    25000 : Total  Size=     100866 bytes  File Size  =      90643 *
*Baskets :        5 : Basket Size=      32000 bytes  Compression=   1.11     *
*............................................................................*
*Br    4 :i         : Float_t                                                *
*Entries :    25000 : Total  Size=     100821 bytes  File Size  =      31885 *
*Baskets :        5 : Basket Size=      32000 bytes  Compression=   3.15     *
*............................................................................*
>>>

What @bellenot suggested is a good option.

As for your question on how to switch to the tree, you can do t = file.name_of_the_tree, and then if you want to know the branches it contains you do t.GetListOfBranches() and you inspect that.

1 Like