convert a dictionary recursively in Python

Viewed 2576

Here is a dictionary:

data = {
    'a': {
        'b': {
            'c': {
                'd': {
                    'e': {
                        'f': 1,
                        'g': 50,
                        'h': [1, 2, 4],
                        'i': 3,
                        'j': [7, 9, 6],
                        'k': [
                            [('x', 'abc')],
                            [('y', 'qwe')],
                            [('z', 'zxc')]
                        ]
                    }
                }
            }
        }
    }
}

My goal is to find and transform values into dictionaries if possible:

data = {
    'a': {
        'b': {
            'c': {
                'd': {
                    'e': {
                        'f': 1,
                        'g': 50,
                        'h': [1, 2, 4],
                        'i': 3,
                        'j': [7, 9, 6],
                        'k': [{
                            'x': 'abc'
                        }, {
                            'y': 'qwe'
                        }, {
                            'z': 'zxc'
                        }]
                    }
                }
            }
        }
    }
}

I think that could be done using recursion and I have even written one, but it doesn't work.

def f(d):
  for key, value in d.iteritems():
    if type(d[key]) is dict:
      f(d)

    try:
      d[key] = dict(d[key])
    except:
      if type(d[key]) is list:
        for i in d[key]:
          try:
            d[key][i] = dict(d[key][i])
          except:
            pass

  return d

The error:

RecursionError: maximum recursion depth exceeded while calling a Python object

How do I make it work?

If you could provide a solution without recursion I'll be glad to get it as well.

2 Answers
Related