【问题标题】:Dynamically create nested dicts using strings from a list [closed]使用列表中的字符串动态创建嵌套字典 [关闭]
【发布时间】:2020-04-02 04:35:06
【问题描述】:

我想根据现有数组创建一个嵌套字典(== javascript 对象)。

例如:

input_array =["hello", "how", "are", "you", "?"]
output_object = 
  { "hello":
    { "how":
      { "are":
        { "you":
          { "?": {}
          }
        }
      }
    }
  }

在 JavaScript 中,解决方案类似于:

for( var i = 0; i < input_array.length; i++ ) {
   output_object[ input_array[i] ] = {};
   output_object = output_object[ input_array[i] ]
};

【问题讨论】:

  • 我想你可以递归地做到这一点。我很好奇这是什么应用。
  • javascript 中的对象 == python 中的字典。 “python 对象”是一个非常不同的概念。另外我应该注意,不需要在标题中添加“Python:”,因为标签会自动将其识别为 python 问题。我已经回滚了你的编辑,希望这能解决问题:)

标签: python json dictionary nested


【解决方案1】:

非常相似:

d = d2 = {}
for i in input_array:
     d2[i] = {}
     d2 = d2[i]

d
# {'hello': {'how': {'are': {'you': {'?': {}}}}}}

【讨论】:

    【解决方案2】:

    你可以使用递归:

    input_array =["hello", "how", "are", "you", "?"]
    def to_dict(d):
      return {d[0]:{} if not d[1:] else to_dict(d[1:])}
    
    output_object = to_dict(input_array)
    

    输出:

    {'hello': {'how': {'are': {'you': {'?': {}}}}}}
    

    【讨论】:

      【解决方案3】:

      使用递归函数:

      >>> def custom_json(array):
          if not array:
              return {}
          else:
              key = array.pop(0)
              return {key : custom_json(array)}
      

      输出:

      >>> input_array =["hello", "how", "are", "you", "?"]
      >>> custom_json(input_array)
      {'hello': {'how': {'are': {'you': {'?': {}}}}}}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-29
        • 2022-11-17
        • 1970-01-01
        • 1970-01-01
        • 2021-04-04
        • 1970-01-01
        相关资源
        最近更新 更多