Flatten nested dictionaries, compressing keys

前端 未结 28 2269
遇见更好的自我
遇见更好的自我 2020-11-22 01:16

Suppose you have a dictionary like:

{\'a\': 1,
 \'c\': {\'a\': 2,
       \'b\': {\'x\': 5,
             \'y\' : 10}},
 \'d\': [1, 2, 3]}

Ho

28条回答
  •  -上瘾入骨i
    2020-11-22 01:47

    def flatten_nested_dict(_dict, _str=''):
        '''
        recursive function to flatten a nested dictionary json
        '''
        ret_dict = {}
        for k, v in _dict.items():
            if isinstance(v, dict):
                ret_dict.update(flatten_nested_dict(v, _str = '_'.join([_str, k]).strip('_')))
            elif isinstance(v, list):
                for index, item in enumerate(v):
                    if isinstance(item, dict):
                        ret_dict.update(flatten_nested_dict(item,  _str= '_'.join([_str, k, str(index)]).strip('_')))
                    else:
                        ret_dict['_'.join([_str, k, str(index)]).strip('_')] = item
            else:
                ret_dict['_'.join([_str, k]).strip('_')] = v
        return ret_dict
    

提交回复
热议问题