I have a dict, and a list describing a path. I want to create a dict, with the dict written to the path. For example:
dog_path = ["animals", "dog"]
dog_content = {
"legs": 4,
}
# desired output
animals = {
"animals": {
"dog": {
"legs": 4,
},
},
}
This is what I have so far. It works for my test cases but thinking perhaps there is a simpler, more pythonic way to do this.
def wrap_dict(path, content):
if not path:
return content
res = {}
d = res
for k in path[:-1]:
d[k] = {}
d = d[k]
d[path[-1]] = content
return res
Any suggestions appreciated!
CodePudding user response:
def wrap_dict(path, content):
return {path[0]: wrap_dict(path[1:], content)} if path else content
wrap_dict(["animals", "dog"], {"legs": 4})
# returns {'animals': {'dog': {'legs': 4}}}
CodePudding user response:
It's perfectly alright, although it would be better if res
, d
and k
had more meaningful names.
Another possible implementation would be using recursion:
def wrap_dict(path, content):
if not path:
return content
return {path[0]: wrap_dict(path[1:], content)}
I think this would be easier to maintain, although I'd guess it would be slightly less performant. If you want to have a path of thousands of items, you might run up against the recursion limit, though.