Convert dictionary recursively in Python

Here is the 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 convert values ​​to 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 this can be done using recursion, and I even wrote one, but it does not 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

Error:

RecursionError: maximum recursion depth exceeded when calling Python object

How can I make it work?

If you could provide a solution without recursion, I would also be happy to receive one.

+4
source share
2 answers

Your program has many errors, allows you to go to them and come up with a working version.

def f(d):
  for key, value in d.iteritems():
    if type(d[key]) is dict:
      f(d)                        # You should call d[key] instead 
    try:
      d[key] = dict(d[key])       # Never assign an object back to the one you are iterating over, create a new object instead.
    except:
      if type(d[key]) is list:
        for i in d[key]:
          try:
            d[key][i] = dict(d[key][i])  # This doesn't work, can't convert a tuple/list this way.
          except:
            pass

  return d

Here is an adjusted version of your code with two recursive functions. One for lists and one for dictionaries.

def f1(value):
  e = []
  for val in value:
    if type(val) is list:
      e += f1(val)               # Append list to current list
    elif type(val) is tuple:
      e.append({val[0]: val[1]}) # Convert tuple to dictionary
    else:
      e.append(val)              # Append normal list values normally
  return e

def f(d, e  = {}):
  for key, value in d.iteritems():
    if type(value) is dict:
      e[key] = f(value, {})     # Recurse for dictionaries
    elif type(value) is list:
      e[key] = f1(value)        # Call the other recursive function for list
    else:
      e[key] = value            # Otherwise like strings and ints just append
  return e

: https://repl.it/LDKn/0

+1

d value, .

:

if type(value) is dict:
    f(value)
0

Source: https://habr.com/ru/post/1685545/


All Articles