convert python list into map


I have a key-value pair say:

key = "a-b-c-d" 
value = 10

using the below command I can convert the key to a list.


so my_list will be like

my_list=['a', 'b', 'c', 'd']

and I want to convert it into a map to have the final output in variable "my_dict" as

my_dict = {'a':{'b':{'c':{'d':10}}}}

so that when I print this




You can set up the base dictionary as the last key with the value, and then iterate the keys in reverse pushing the dictionary as the value for the new key:

key = "a-b-c-d" 
value = 10
keys = key.split('-')
d = value
for k in keys[::-1]:
    d = { k : d }
# {'a': {'b': {'c': {'d': 10}}}}
# 10

Answered By – Nick

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published