Recursively modify a dictionary
<p>I've created a class that should transform a nested list into a dictionary. The following is my input:</p>

<pre><code>['function:and',
    ['variable:X', 'function:&gt;=', 'value:13'],
    ['variable:Y', 'function:==', 'variable:W']]
</code></pre>

<p>And the output should be a dictionary in the following form:</p>

<pre><code>{
  "function": "and",
  "args": [
    {
      "function": "&gt;=",
      "args": [
        {
          "variable": "X"
        },
        {
          "value": 13
        }
      ]
    },
    {
      "function": "==",
      "args": [
        {
          "variable": "Y"
        },
        {
          "variable": "W"
        }
      ]
    }
  ]
}
</code></pre>

<p>This is the class that receives the input list and should return the required dictionary.</p>

<pre><code>class Tokenizer(object):
    def __init__(self, tree):
        self.tree = tree
        self.filter = {}

    def to_dict(self, triple):
        my_dict = {}
        try:
            first = triple[0]
            second = triple[1]
            third = triple[2]
        except KeyError:
            return
        if type(second) == str and type(third) == str:
            my_dict['function'] = second.split(':')[-1]
            my_dict['args'] = [
                {first.split(':')[0]: first.split(':')[1]},
                {third.split(':')[0]: third.split(':')[1]}]
        # case recursive
        if type(second) == list:
            my_dict['function'] = first.split(':')[-1]
            my_dict['args'] = [second, third]
        return my_dict

    def walk(self, args):
        left = self.to_dict(args[0])
        right = self.to_dict(args[1])
        if isinstance(left, dict):
            if 'args' in left.keys():
                left = self.walk(left['args'])
        if isinstance(right, dict):
            if 'args' in right.keys():
                right = self.walk(right['args'])
        args = [left, right]
        return args

    def run(self):
        self.filter.update(self.to_dict(self.tree))
        if 'args' in self.filter.keys():
            self.filter['args'] = self.walk(self.filter['args'])


tree = [
    'function:and',
        ['variable:X', 'function:&gt;=', 'value:13'],
        ['variable:Y', 'function:==', 'variable:W']
    ]

import pprint
pp = pprint.PrettyPrinter(indent=4)
t = Tokenizer(tree)
t.run()
pp.pprint(t.filter)
</code></pre>

<p>My recursive method <code>walk</code> is not doing what it should be and I'm a total sucker in recursion so I can't figure what I'm doing wrong. </p>

<p>The output I'm getting is:</p>

<pre><code>{   'args': [[None, None], [None, None]], 'function': 'and'}
</code></pre>

<p>For your particular test case you don't need to go into recursion at all. You can comment out your calls:</p>

<pre><code>def walk(self, args):
    left = self.to_dict(args[0])
    right = self.to_dict(args[1])
    #if isinstance(left, dict):
    #    if 'args' in left.keys():
    #        left = self.walk(left['args'])
    #if isinstance(right, dict):
    #    if 'args' in right.keys():
    #        right = self.walk(right['args'])
    args = [left, right]
    return args
</code></pre>

<p>and get the desired output.
You only need to go into recursion if you allow for nested functions in your input:</p>

<pre><code> ['function:and',
      ['variable:X', 'function:&gt;=', 'value:13'],
      ['function:==',
          ['variable:R', 'function:&gt;=', 'value:1'],
          ['variable:Z', 'function:==', 'variable:K']
      ]
 ]
</code></pre>

<p>then you have to check for a base case, so you go into recursion only if your <code>args</code> key's value contains unprocessed values:</p>

<pre><code>def walk(self, args):
    left = self.to_dict(args[0])
    right = self.to_dict(args[1])
    if isinstance(left, dict):
        if 'args' in left.keys() and isinstance(left['args'][0], list):
            left = self.walk(left['args'])
    if isinstance(right, dict):
        if 'args' in right.keys() and isinstance(right['args'][0], list):
            right = self.walk(right['args'])
    args = [left, right]
    return args
</code></pre>

<p>and then you'll get this:</p>

<pre><code>{   'args': [   {   'args': [{   'variable': 'X'}, {   'value': '13'}],
                'function': '&gt;='},
            {   'args': [   {   'args': [   {   'variable': 'R'},
                                            {   'value': '1'}],
                                'function': '&gt;='},
                            {   'args': [   {   'variable': 'Z'},
                                            {   'variable': 'K'}],
                                'function': '=='}],
                'function': '=='}],
'function': 'and'}
</code></pre>

<p>Also it would be easier if your input list was a regular structure that consistently had argument fields following function name field. You could then significantly simplify your <code>to_dict</code> method.</p>

python algorithm dictionary recursion