pythonmayapymel

Create a recursive function to get hierarchy in maya


Hi i am trying to get the hierarchy of the scene file in maya as a dictionary. For example enter image description here

I want this data as a dictionary

tree = {"group5": {"group4": {"group3": {"group2": {"group1": {"pSphere1": "pSphere1Shape"}},
                                     "pSphere2": {"pSphere2Shape"}
                                     }
                          }
               },
    "group8": {"group7": {"group6": {"pCube": {"pCube1Shape"}
                                     }
                          }
               }
    }

Any suggession as how to get this data?


Solution

  • I don't usually write recursive functions so I gave it a shot for fun

    import pymel.core as pm
    
    def getHierarchy(start):
        dict = {}
        startNode = pm.PyNode(start)
        #print dir(startNode)
        children = startNode.getChildren()
        if children:
            for child in children:
                dict[child.name()] = getHierarchy(child.name())
        
        return dict
        
    
    if __name__ == '__main__':
        sel = pm.selected()[0]
        hierarchyDict = { sel.name() : getHierarchy(sel.name())}
        print hierarchyDict
    

    results:

    {u'group5': {u'group4': {u'group3': {u'group2': {u'group1': {u'pSphere1': {u'pSphereShape1': {}}}, u'pSphere2': {u'pSphereShape2': {}}}}}, u'group8': {u'group7': {u'group6': {u'pCube1': {u'pCubeShape1': {}}}}}}}
    

    other than your brace spacing/newlines, I noticed that in your example the shape nodes(leaves of your tree) don't look like a proper dictionary. in this example I have them end as a key to an empty dict. edit: oops it doesn't include the start point "group5" I'll add it in the boiler plate, maybe someone could point out how to make it better