Flatten nested dictionaries, compressing keys

前端 未结 28 2242
遇见更好的自我
遇见更好的自我 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条回答
  •  抹茶落季
    2020-11-22 01:46

    def flatten(unflattened_dict, separator='_'):
        flattened_dict = {}
    
        for k, v in unflattened_dict.items():
            if isinstance(v, dict):
                sub_flattened_dict = flatten(v, separator)
                for k2, v2 in sub_flattened_dict.items():
                    flattened_dict[k + separator + k2] = v2
            else:
                flattened_dict[k] = v
    
        return flattened_dict
    

提交回复
热议问题