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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With