【问题标题】:Need to create a layered dict from a flat one需要从平面创建分层字典
【发布时间】:2023-03-25 19:23:01
【问题描述】:

我有一个字典,看起来像这样:

{
    'foo': {
        'opt1': 1,
        'opt2': 2,
        },
    'foo/bar': {
        'opt3': 3,
        'opt4': 4,
        },
    'foo/bar/baz': {
        'opt5': 5,
        'opt6': 6,
        }
    }

我需要让它看起来像:

{
    'foo': {
        'opt1': 1,
        'opt2': 2,
        'bar': {
            'opt3': 3,
            'opt4': 4,
            'baz': {
                'opt5': 5,
                'opt6': 6,
                }
            }
        }
    }

我应该指出,可以并且将会有多个顶级键(在本例中为“foo”)。我可能会拼凑一些东西来获得我需要的东西,但我希望有一个更有效的解决方案。

【问题讨论】:

    标签: python algorithm performance


    【解决方案1】:

    让这个库以更好的方式打印您的字典。 pprinthttps://docs.python.org/3.2/library/pprint.html

    【讨论】:

      【解决方案2】:
      def layer(dict):
        for k,v in dict:
          if '/' in k:
            del dict[k]
            subdict = dict.get(k[:k.find('/')],{})
            subdict[k[k.find('/')+1:]] = v
            layer(subdict)
      

      【讨论】:

        【解决方案3】:

        像这样:

        def nest(d):
            rv = {}
            for key, value in d.iteritems():
                node = rv
                for part in key.split('/'):
                    node = node.setdefault(part, {})
                node.update(value)
            return rv
        

        【讨论】:

        • 以大 O 表示法添加运行时会更好:)
        • M = sum(len(key.split('/')) for key in d); # 运行时间为 O(M)
        猜你喜欢
        • 1970-01-01
        • 2020-07-06
        • 2021-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-15
        • 2018-11-09
        相关资源
        最近更新 更多