【问题标题】:Create a new dict with a given dict written to given path使用写入给定路径的给定字典创建一个新字典
【发布时间】: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


【解决方案1】:
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}}}

【讨论】:

    【解决方案2】:

    没关系,不过如果resdk 有更有意义的名称会更好。

    另一种可能的实现是使用递归:

    def wrap_dict(path, content):
        if not path:
            return content
        return {path[0]: wrap_dict(path[1:], content)}
    

    我认为这会更容易维护,尽管我猜它的性能会稍差一些。但是,如果您想拥有包含数千个项目的路径,则可能会遇到递归限制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 2019-01-16
      • 2020-09-21
      • 2016-12-28
      相关资源
      最近更新 更多