【问题标题】:How to create a nested dictionary from a list in Python?如何从 Python 中的列表创建嵌套字典?
【发布时间】:2016-11-03 12:46:26
【问题描述】:

我有一个字符串列表:tree_list = ['Parents', 'Children', 'GrandChildren']

如何获取该列表并将其转换为这样的嵌套字典?

tree_dict = {
    'Parents': {
        'Children': {
            'GrandChildren' : {}
        }
    }
}

print tree_dict['Parents']['Children']['GrandChildren']

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    这个最简单的方法是从内到外构建字典:

    tree_dict = {}
    for key in reversed(tree_list):
        tree_dict = {key: tree_dict}
    

    【讨论】:

      【解决方案2】:

      使用递归函数:

      tree_list = ['Parents', 'Children', 'GrandChildren']
      
      def build_tree(tree_list):
          if tree_list:
              return {tree_list[0]: build_tree(tree_list[1:])}
          return {}
      
      build_tree(tree_list)
      

      【讨论】:

        【解决方案3】:

        这是一个简短的解决方案:

        lambda l:reduce(lambda x,y:{y:x},l[::-1],{})
        

        【讨论】:

        • @Chris_Rands 啊,我完全同意你的看法。但可读性只是一个标准。
        • 您可以通过将{} 作为第三个参数传递给reduce() 来保存两个字符,而不是将其添加到列表中。
        • @Sven Marnach 好!
        猜你喜欢
        • 1970-01-01
        • 2016-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多