# Loop over all objects in a ROOT file

**URL:** <https://root-forum.cern.ch/t/loop-over-all-objects-in-a-root-file/10807>\
**Category:** ROOT\
**Created:** [August 20, 2010, 11:28am UTC](https://root-forum.cern.ch/t/loop-over-all-objects-in-a-root-file/10807 "2010-08-20T11:28:32Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![odysei](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/o/51bf81/32.png) [@odysei](https://root-forum.cern.ch/u/odysei)\
**Post date:** [September 27, 2017, 10:46am UTC](https://root-forum.cern.ch/t/loop-over-all-objects-in-a-root-file/10807/5 "2017-09-27T10:46:15Z")

</div>

Since I found both replies being broken in my case. In particular, IsFolder() returns True for TTree, GetListOfKeys() chokes with TTree, etc, so pasting my longer solution here:

```python
import ROOT

def Map(tf, browsable_to, tpath=None):
    """
    Maps objets as dict[obj_name][0] using a TFile (tf) and TObject to browse.
    """
    m = {}
    for k in browsable_to.GetListOfKeys():
        n = k.GetName()
        if tpath == None:
            m[n] = [tf.Get(n)]
        else:
            m[n] = [tf.Get(tpath + "/" + n)]
    return m

def Expand_deep_TDirs(tf, to_map, tpath=None):
    """
    A recursive deep-mapping function that expands into TDirectory(ies)
    """
    names = sorted(to_map.keys())
    for n in names:
        if len(to_map[n]) != 1:
            continue
        if tpath == None:
            tpath_ = n
        else:
            tpath_ = tpath + "/" + n
        
        tobject = to_map[n][0]
        if type(tobject) is ROOT.TDirectoryFile:
            m = Map(tf, tobject, tpath_)
            to_map[n].append(m)
            Expand_deep_TDirs(tf, m, tpath_)

def Map_TFile(filename, deep_maps=None):
    """
    Maps an input file as TFile into a dictionary(ies) of objects and names.
    Structure: dict[name][0] == object, dict[name][1] == deeper dict.
    """
    if deep_maps == None:
        deep_maps = {}
    if not type(deep_maps) is dict:
        return deep_maps
    
    f = ROOT.TFile(filename)
    m = Map(f, f)
    Expand_deep_TDirs(f, m)

    deep_maps[filename] = [f]
    deep_maps[filename].append(m)
    
    return deep_maps

```

---

_[View the full topic](https://root-forum.cern.ch/t/loop-over-all-objects-in-a-root-file/10807)._
