Rohit
Rohit

Reputation: 10286

Get nested dictionary

I have a datarow in excel as

'Ars','Cr','Assl','Burg','Consp'

I want to convert it into nested dictionary like this

 data_dict.update({'name':'Ars','children':[{
                  'name':'Cr','children':[{
                  'name':'Assl','children':[{
                  'name':'Burg','children':[{
                  'name':'Consp','children':[{
                  'none'}]}]}]}]}]}

I am trying to write a recursive method to update my dictionary

def update(row,idx,data_dict):
   if idx==len(row):
     return data_dict
  else:
     data_dict.update({'name':row[idx],'children':update(row,idx+1,{})}

I am pretty sure the last line is wrong but I cant figure out a way to create this structure

P.S updated the question to include square brackets Thanks

Upvotes: 1

Views: 48

Answers (2)

Dani Mesejo
Dani Mesejo

Reputation: 61930

You could use reduce:

from functools import reduce

keys = ['Ars', 'Cr', 'Assl', 'Burg', 'Consp']

result = reduce(lambda x, y: {"name": y, "children": x}, reversed(keys), None)
print(result)

Output

{'name': 'Ars', 'children': {'name': 'Cr', 'children': {'name': 'Assl', 'children': {'name': 'Burg', 'children': {'name': 'Consp', 'children': None}}}}}

UPDATE

If you need brackets do the following:

from functools import reduce

keys = ['Ars', 'Cr', 'Assl', 'Burg', 'Consp']

result = reduce(lambda x, y: {"name": y, "children": [x]}, reversed(keys), None)
print(result)

Output

{'name': 'Ars', 'children': [{'name': 'Cr', 'children': [{'name': 'Assl', 'children': [{'name': 'Burg', 'children': [{'name': 'Consp', 'children': [None]}]}]}]}]}

Basically just add brackets around x in the lambda function.

Upvotes: 2

Alex
Alex

Reputation: 19124

l = ['Ars','Cr','Assl','Burg','Consp']

d_ = d = {}

for name, val in zip(l, l[1:]):
    d['name'] = val
    d['children'] = d = {}

d_

evaluates to

{'name': 'Cr',
 'children': {'name': 'Assl',
  'children': {'name': 'Burg', 'children': {'name': 'Consp', 'children': {}}}}}

Upvotes: 0

Related Questions