2

I have list of keys: list1 =['info', 'websites', 'site'] and a final value = 'check'. I'm trying to build a recursive function that create a nested dictionary as follows:

dict = {'info': {'websites': {'site' : 'check' } } } 

I tried the following function but my function doesn't get the above output:

def nested_dict(keys_list, value, check_dict, size): if size != 1: print(check_dict) check_dict[keys_list[0]] = nested_dict(keys_list[1:], value, check_dict, size-1) else: print(check_dict) check_dict[keys_list[0]] = value return check_dict 

I appreciate your help!

1
  • Is your indentation correct? In case of if you are not returning anything Commented Oct 18, 2021 at 12:16

4 Answers 4

6

There is no need for recursion. This will work:

list1 = ['info', 'websites', 'site'] def nested_dict(keys_list, value): for key in reversed(keys_list): value = {key: value} return value print(nested_dict(list1, 'check')) 

gives:

{'info': {'websites': {'site': 'check'}}} 

If you use recursion, there is a danger of exceeding the maximum recursion depth for long lists, for little advantage.

Sign up to request clarification or add additional context in comments.

Comments

4

I don't know why you are using so many arguments in your nested_dict function. You don't need them there. This simple example gives me the result you are looking for:

def nested_dict(keys): if(len(keys) == 1): return {keys[0]: 'check'} else: return {keys[0]: nested_dict(keys[1:])} key_list = ['info', 'websites', 'site'] print(nested_dict(key_list)) 

Also, yes, as has been posted above you don't need recursion to do just this. But for my answer I assumed you need the recursion for another part of your project anyway.

3 Comments

Yes, thank you for this answer. Although I thought it is helpful to show an answer without recursion, it is also helpful to show how the recursive solution can be implemented properly.
That said, you might also like to look at sushant's answer. There is a slightly different stop condition, and that one allows for the possibility of an empty list of keys, which yours doesn't.
Ah, yes, that is a good point, thanks :)!
4

A functional approach using functools.reduce:

from functools import reduce lst = ['info', 'websites', 'site'] result = reduce(lambda x, y: {y: x}, reversed(lst), "check") print(result) 

Output

{'info': {'websites': {'site': 'check'}}} 

Comments

2

You can use recursive function like so:

>>> list1 =['info', 'websites', 'site'] def nested_dict(l, value): if not l: return value else: return {l[0]: nested_dict(l[1:])} >>> nested_dict(list1, 'check') {'info': {'websites': {'site': 'check'}}} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.