How to completely traverse a complex dictionary of unknown depth?

后端 未结 7 1972
深忆病人
深忆病人 2020-11-30 17:35

Importing from JSON can get very complex and nested structures. For example:

{u\'body\': [{u\'declarations\': [{u\'id\': {u\'name\': u\'i\',
            


        
7条回答
  •  生来不讨喜
    2020-11-30 18:32

    If the accepted answer works for you, but you'd also like a full, ordered path with the numerical index of the nested arrays included, this slight variation will work:

    def dict_generator(indict, pre=None):
        pre = pre[:] if pre else []
        if isinstance(indict, dict):
            for key, value in indict.items():
                if isinstance(value, dict):
                    for d in dict_generator(value,  pre + [key]):
                        yield d
                elif isinstance(value, list) or isinstance(value, tuple):
                    for k,v in enumerate(value):
                        for d in dict_generator(v, pre + [key] + [k]):
                            yield d
                else:
                    yield pre + [key, value]
        else:
            yield indict
    

提交回复
热议问题