How To Get List Of Dict Instead Of Using Collection.defaultdict In Python
I am trying to convert a list into nested dictionaries recursively as following :- Given Input :- parse_list = ['A','B','C','D'] Required Output :- data = [ {'name': 'A',
Solution 1:
You can acheive it simply like this
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': [{}]
}]}]}]}
Solution 2:
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())
Solution 3:
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)
Post a Comment for "How To Get List Of Dict Instead Of Using Collection.defaultdict In Python"