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