Nuke Python list of objects order based on other list
<p>I got two lists. First one looks like this:</p>

<pre><code>passOrder = [
                    'direct_diffuse',
                    'direct_specular',
                    'direct_specular_2',
                    'indirect_diffuse',
                    'indirect_specular',
                    'indirect_specular_2',
                    'refraction',
                    'reflection',
                    'emission',
                    'sss'
                ]
</code></pre>

<p>and the other one is a list of objects - in this case Nuke nodes:</p>

<pre><code>nodes = nuke.selectedNodes()
</code></pre>

<p>I'm trying to compare each node's name parameter with passOrder list and arrange them in the order given in passOrder. I tried to explicitly set up orderedNodes index but I guess it's not possible when the list is empty at start.</p>

<pre><code>orderedNodes = []
for n in nodes:
    for index, p in enumerate(passOrder):
        if n['name'].value() == p:
            orderedNodes.insert(index, n)
</code></pre>

<p>I've also tried to zip both lists, and sort them - no luck here. Basically I have no idea how to iterate over <code>n['name'].value()</code> component when sorting.</p>

<p>You can construct a dictionary mapping node names to nodes like this</p>

<pre><code>nodes_by_name = {n['name'].value(): n for n in nodes}
</code></pre>

<p>With this dictionary, it's trivial to retrieve the nodes in the desired order:</p>

<pre><code>ordered_nodes = [nodes_by_name[name] for name in passOrder]
</code></pre>

<p>If there might be names in <code>passOrder</code> without corresponding nodes, you can simply skip them:</p>

<pre><code>ordered_nodes = [nodes_by_name[name] for name in passOrder if name in nodes_by_name]
</code></pre>

<p>This approach is simpler and more efficient than trying to use sorting.</p>

python list sorting object nuke