Search code examples
pythonlistdictionarygraphmaya

How to walk on a dictionary which represent a graph and return a list of element


I have a problem and I can not find a solution.

I have a graph like this:

The node graph in Maya

I have function which return the graph like this:

    data = {
    'Finition': {
        'Metal': {
            'colorCorrect1': {
                'Color': {
                    'aiLayerShader2': {
                        'colorConstant1': {},
                        'colorConstant3': {},
                        'colorConstant2': {
                            'aiFloatToRgba1': {
                                'place2dTexture1': {}
                                }
                            },
                        'colorConstant4': {},
                        'colorConstant5': {
                            'aiFloatToRgba1': {
                                'place2dTexture1': {}
                                }
                            },
                        'colorConstant6': {}
                        }
                    }
                }
            }
        }
    }

I have a list of main groups (Blues Nodes in the picture): `

    selection = ['Finition', 'Metal', 'Color', 'colorConstant2']

I need a function that can return me the list of nodes (before the next group) for a specific group:

The return value should be like this:

    [
        ['Finition'],
        ['Metal', 'colorCorrect1'],
        ['Color', 'aiLayerShader2', 'colorConstant1', 'colorConstant3', 'colorConstant4', 'colorConstant5', 'colorConstant6', 'aiFloatToRgba1', 'place2dTexture1'],
        ['colorConstant2', 'aiFloatToRgba1', 'place2dTexture1']
    ]

I tried the following:

    def search_recurssive(element=None, main={}, depth=0):
        for key, value in main.items():
            if key != element:
                if isinstance(value, dict):
                    search_recurssive(element=element, main=value, depth=depth+1)
            else:
                pprint(value)
                print depth

    search_recurssive(element='Metal', main=data)

But it did not work. What can I try next?


Solution

  • Here is a rather inefficient method:

    def getChildren(data,s):
        global selection
        res = [s]
        for child in data[s].keys():
            if child in selection:
                continue
            else:
                res.extend(getChildren(data[s], child))
        return res
    
    def getDataPart(data,s):
        for key in data.keys():
            if key == s:
                return data
            res = getDataPart(data[key],s)
            if res is not None:
                return res
    
    results = []
    
    for s in selection:
        data_part = getDataPart(data,s)
        results.append(getChildren(data_part,s))