Ron Fisher
Ron Fisher

Reputation: 45

create nested dictionary from keys list

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!

Upvotes: 2

Views: 136

Answers (4)

Dani Mesejo
Dani Mesejo

Reputation: 61910

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'}}}

Upvotes: 4

sushant
sushant

Reputation: 1111

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'}}}

Upvotes: 2

Graphsicle
Graphsicle

Reputation: 41

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.

Upvotes: 4

alani
alani

Reputation: 13079

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.

Upvotes: 6

Related Questions