【问题标题】:Building a nested python Dictionary from list从列表构建嵌套的python字典
【发布时间】:2017-08-08 10:48:25
【问题描述】:

我有一个长度不同的字符串,我想创建一个嵌套字典。到目前为止我有这个,但似乎无法弄清楚如何克服可变深度问题。

    string = "a/b/c/b"
    x = string.split('/')
    y = {}
    for item in x:
      y[item] = dict()
      .............

我尝试了许多不同的方法,但只是不知道如何动态构建它。我想得到的最终结果是:

{'a' :{'b' : {'c': {'d': {}}}}

希望得到一些关于设计和想法的反馈,以实现这一目标。

谢谢,

【问题讨论】:

    标签: python loops dictionary nested


    【解决方案1】:

    只需更新循环如下:

    y = {}
    for item in reversed(x):
        y = {item: y}
    

    【讨论】:

      【解决方案2】:

      @ozgur's answer 的单行缩减版

      >>> string = "a/b/c/d"
      >>> reduce(lambda x, y: {y: x}, reversed(string.split('/')), {})
      {'a': {'b': {'c': {'d': {}}}}}
      

      但我更喜欢@ozgur 的原始答案

      【讨论】:

      • 我更喜欢您删除的第一个答案。如果您最终不得不处理迭代器/生成器,那么依赖 reversed() 可能会出现问题,但这超出了 OP 问题的范围。
      • @AChampion reversed 看起来很简单。但这是一个很好的观点,虽然很少见,但可能有一个生成器或迭代器需要您单步执行
      【解决方案3】:

      试试这个:

      string = "a/b/c/b"
      x = string.split('/')
      x.reverse()
      y = {}
      count=0
      for item in x:
          if count==0:
              tmp={item:{}}
          else:
              tmp={item: tmp}
          count+=1
      print tmp
      

      输出:

      {'a': {'b': {'c': {'b': {}}}}}
      

      【讨论】:

        【解决方案4】:
        >>> text = 'a/b/c/d'
        >>> d = node = {}
        >>> for c in text.split('/'):
        ...   node = node.setdefault(c, {})
        ... 
        >>> d
        {'a': {'b': {'c': {'d': {}}}}}
        

        【讨论】:

        • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
        【解决方案5】:

        一种简单的方法是递归:

        def fn(s):
            if not s:
                return {}
            x, *y = s   # Python3, for Python2 x, y = s[0], s[1:]
            return {x:fn(y)}
        
        >>> fn("a/b/c/b".split('/'))
        {'a': {'b': {'c': {'b': {}}}}}
        

        但是如果你想迭代地做那么你就很接近了,只需使用光标沿着结构向下走:

        >>> y = {}
        >>> c = y
        >>> for item in "a/b/c/b".split('/'):
        ...     c[item] = {}
        ...     c = c[item]
        >>> y
        {'a': {'b': {'c': {'b': {}}}}}
        

        【讨论】:

          猜你喜欢
          • 2021-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-04
          • 1970-01-01
          • 2021-11-25
          • 1970-01-01
          相关资源
          最近更新 更多