Loop through branches - pyROOT

Hi!

I’m reading the event information in a tree and I want to make my code more efficient by calling the branches inside a loop, instead of having to write out each branch name. But I have not figured out how to get the actual values from the branch, because it takes the branch name variable as a string and not as the object.

    branches = ["monEta", "monPhi", "monMass", "monPdgId"]
    for i, ev in enumerate(tree):
        if i > 10:
            break
        for j, b in enumerate(branches):
            for n in range(0,ev.b.size()):
                print ev.b.at(n)

The ev.b.size() prompts the first error, which means ev.b.at(n) is also problematic:

AttributeError: 'TTree' object has no attribute 'b'

I’ve also attempted using for b in tree.GetListOfBranches(): instead, but get the same error.
Tried uploading test ntuple but the file is too large. Hopefully it is easily reproducible with a different one.
Thank you in advance.LoopinBranches.py (1.3 KB)

Hello,

The code you pasted is trying to access a branch with name “b”. I understand what you want is to access the branches whose name is stored in variable b, for that you can do getattr(ev, b) instead of ev.b.

1 Like

Thank you! This works perfect!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.