python实现字典转换

有下面的一道算法题,使用python实现,一直没有思路,请各位大神给一点思路好么

实现flatten函数,有如下功能:
nested_json = {
        "a": 1,
        "b": [35, 26],
        "c": [{
                "d": [2, 3, 4],
                "e": [
                    {
                        "f": 1,
                        "g": 2
                        }
                    ]
            }],
        "h": {}
        }
    
    flattened_json = flatten(nested_json)
        

    print(flattened_json)
    {'a': 1,
     'b.0': 35,
     'b.1': 26,
     'c.0.d.0': 2,
     'c.0.d.1': 3,
     'c.0.d.2': 4,
     'c.0.e.0.f': 1,
     'c.0.e.0.g': 2,
     'h': {}
    }
阅读 388
评论 2019-05-29 提问
    3 个回答
    prolifes
    • 11.1k

    这道题不是考算法,而是考个人对python各种语法、函数的熟悉程度

    # coding: utf-8
    # __author__: 'Rich'
    
    from __future__ import unicode_literals
    
    
    def flatten(d, parent_key=None, out={}):
        for k, v in d.items():
            if not isinstance(v, list):
                key = '{}.{}'.format(parent_key, k) if parent_key else k
                out[key] = v
                continue
    
            for i, v1 in enumerate(v):
                key = '{}.{}.{}'.format(parent_key, k, i) if parent_key else '{}.{}'.format(k, i)
                if not isinstance(v1, dict):
                    out[key] = v1
                    continue
    
                flatten(v1, key, out)
    
        return out
    
    
    nested_json = {
        "a": 1,
        "b": [35, 26],
        "c": [{
                "d": [2, 3, 4],
                "e": [
                    {
                        "f": 1,
                        "g": 2
                        }
                    ]
            }],
        "h": {}
    }
    
    flattened_json = flatten(nested_json)
    print(flattened_json)
    评论 赞赏 2019-05-30

      麻烦可以详细说一下你的需求吗?

      评论 赞赏 2019-05-30

        供参考.

        代码:

        #!/usr/bin/env python
        
        from collections import namedtuple
        from collections.abc import Iterable
        
        Node = namedtuple("Node", ["keys", "value"])
        Node.__new__.__defaults__ = ((), None)
        
        def flattern(nested):
            def dfs(node):
                ks, nv = node
                if nv and isinstance(nv, Iterable):
                    if type(nv) == list:
                        kvs = enumerate(nv)
                    elif type(nv) == dict:
                        kvs = nv.items()
                    for k, v in kvs:
                        n = Node(keys=ks+(str(k),), value=v)
                        yield from dfs(n)
                else:
                    yield node
        
            root = Node(keys=(), value=nested)
            return {'.'.join(keys):value for keys, value in dfs(root)}
        
        
        评论 赞赏 2019-06-05
          撰写回答

          登录后参与交流、获取后续更新提醒

          社区建设
          合作问答

          欢迎来到 SegmentFault 0x 社区建设。这里可以讨论有关 SegmentFault 的一切,帮助我们改进产品、完善社...