0

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
Amit Kumar
  • 313
  • 1
  • 4
  • 14

3 Answers3

1

Probably not the ideal way, but I would approach it like this:

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

*parts, last_part = key.split('-')

my_dict = temp = {}

for part in parts:
    temp[part] = temp = {}

# assign last part, {d: 10}
temp[last_part] = value

print(my_dict)

Result:

{'a': {'b': {'c': {'d': 10}}}}
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
1

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 reversed(keys):
    d = { k : d }
print(d)
# {'a': {'b': {'c': {'d': 10}}}}
print(d['a']['b']['c']['d'])
# 10
Nick
  • 138,499
  • 22
  • 57
  • 95
  • 1
    instead of keys[::-1], better to use reversed(keys) – Amit Kumar Jun 11 '22 at 14:14
  • 1
    @AmitKumar you make an interesting point. Out of curiosity I tested it with lists of keys up to 1000000 entries and found - at least on my computer - that for this code there was no significant difference between the two performance wise as the majority of the time is taken on the `d = { k : d }` assignment. However replacing statement that with `pass` does show `reversed` to be about 25% faster and of course there is a memory space benefit. Thanks for pointing this out, I learned something useful today. Answer edited appropriately. – Nick Jun 11 '22 at 23:20
-1

Build the dictionary by iterating through the list of keys in reverse. On the first iteration, when the dictionary is empty, assign the innermost key, value pair. Then increase the dictionary iteratively, using copy.

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

my_dict = {}
for k in my_list[::-1]:
    if not my_dict:
        my_dict[k] = value
    else:
        my_dict = {k: my_dict.copy()}

print(my_dict)
# {'a': {'b': {'c': {'d': 10}}}}
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47