convert python list into map

Issue

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.

my_list=key.split("-")

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

print(my_dict['a']['b']['c']['d'])

10

Solution

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 }
print(d)
# {'a': {'b': {'c': {'d': 10}}}}
print(d['a']['b']['c']['d'])
# 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