How to get a list of dict instead of using collection.defaultdict in python

I am trying to convert a list to nested dictionaries recursively like this: -

Given input: -

parse_list = ['A','B','C','D'] 

      

Desired output: -

data = [
    {'name': 'A',
     'childs': [
         {'name': 'B',
          'childs': [
              {'name': 'C',
               'childs': [
                   {'name': 'D',
                    'childs': none }]}]}]}]

      

My code: -

from collections import defaultdict
class_dict =defaultdict(list)
data =defaultdict(list)
parse_list.reverse()

def create_dict(parse_list,class_dict):
    for index ,listitem in enumerate(parse_list):
        new_class_dict = defaultdict(list)
        new_class_dict.__setitem__('name', listitem)
        new_class_dict['childs'].append(class_dict)
        class_dict = new_class_dict
    return class_dict

data = create_dict(parse_list,class_dict) 
import yaml
with open('data.yml', 'w') as outfile:
    outfile.write( yaml.dump(data, default_flow_style=False))

      

However, due to defaultdict (list), I always get a lot of extra padding in the yaml, which is not expected. Is there any other way to get [{....}] instead of using collection.defaultdict.

+1


source to share


3 answers


In a recursive way



parse_list = ['A','B','C','D']



def createdict(l, d):
    if len(l) == 0:
        return None
    d = dict()
    d['name'] = l[0]
    d['childs'] = [createdict(l[1:], d)]
    return d

resultDict = createdict(parse_list, dict())

      

0


source


You can achieve it just like that



parse_list = ['A','B','C','D']

dicton={}

for i in reversed(parse_list):
    dicton['child']=[dicton]
    dicton['name']=i


print dicton
#output {'name': 'A', 
         'child': [{'name': 'B', 
                     'child': [{'name': 'C', 
                                'child': [{'name': 'D', 
                                            'child': [{}]
                                                         }]}]}]}

      

+2


source


Here's a recursive solution

parse_list = ['A','B','C','D']

def descend(l):
    if l:
        return [{'name': l[0],
                'childs': descend(l[1:])}]
    else:
        return None

data = descend(parse_list)

      

0


source







All Articles