Home > Net >  String array to nested dictionary Python
String array to nested dictionary Python

Time:04-23

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

CodePudding user response:

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

CodePudding user response:

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))
  • Related