0

I'm a begginer in python and I want to make this:

I have a string array I want to make a dictionary with string as keys, but this way: Transform this:

 ['Users', 'ID', 'Age']

Into this:

{
    'Users': {
        'ID': {
            'Age': None
        }
    }
}
2

2 Answers 2

1

You could do this like so:

def tranform_list_to_dict(lst):
    new = {}
    for item in lst[::-1]:
        if not new:
            new[item] = None
        else:
            tmp = {}
            tmp[item] = new.copy()
            new = dict(tmp)
    return new


my_list = ['Users', 'ID', 'Age']
print(tranform_list_to_dict(my_list))

Which will produce:

{
    "Users": {
        "ID": {
            "Age": None
         }
     }
}
Sign up to request clarification or add additional context in comments.

Comments

0

you may do this

list1 = ['User', 'ID', 'Age']

def transform(alist):
    alist = alist[::-1]
    dic = {alist[0]: None}
    for i in range(len(alist)-1):
        dic = {alist[i]: dic}
    return dic

print(transform(list1))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.