【发布时间】:2021-09-24 16:55:53
【问题描述】:
我有一个字典和一个描述路径的列表。我想创建一个字典,将字典写入路径。例如:
dog_path = ["animals", "dog"]
dog_content = {
"legs": 4,
}
# desired output
animals = {
"animals": {
"dog": {
"legs": 4,
},
},
}
这是我目前所拥有的。它适用于我的测试用例,但我想也许有一种更简单、更 Pythonic 的方式来做到这一点。
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
任何建议表示赞赏!
【问题讨论】:
-
这似乎够pythonic了。
-
单线:
from functools import reduce; res = reduce(lambda d, k: {k: d}, reversed(path), content).
标签: python dictionary