I have a value test-1
and a list of keys as below:
[
["initial", "short_title"],
["later", "datasets", "item_okmiwt"],
["general_title"]
]
I wanted the resulting dictionary like this:
{'initial': {'short_title': 'test-1'}, 'later': {'datasets': {'item_okmiwt': 'test-1'}}, 'general_title': 'test-1'}
I have written the following code for implementing the above result:
def set_copy_to_attr(value, copy_to_attr):
"""Method to copy value to copy_to config."""
def build_nested_dict(element, result={}):
if len(element) == 1:
result[element[-1]] = pid_value
return result
else:
for el in element:
result[el] = {}
element.remove(el)
build_nested_dict(element, result[el])
for _element in copy_to_attr:
_dict = build_nested_dict(_element)
if _dict:
return _dict
I am getting the desired result, Is this approach can be optimized more?