Creating a nested dictionary from a flattened dictionary

后端 未结 7 2014
-上瘾入骨i
-上瘾入骨i 2020-12-15 02:43

I have a flattened dictionary which I want to make into a nested one, of the form

flat = {\'X_a_one\': 10,
        \'X_a_two\': 20, 
        \'X_b_one\': 10,         


        
7条回答
  •  时光说笑
    2020-12-15 03:19

    Here is my take:

    def nest_dict(flat):
        result = {}
        for k, v in flat.items():
            _nest_dict_rec(k, v, result)
        return result
    
    def _nest_dict_rec(k, v, out):
        k, *rest = k.split('_', 1)
        if rest:
            _nest_dict_rec(rest[0], v, out.setdefault(k, {}))
        else:
            out[k] = v
    
    flat = {'X_a_one': 10,
            'X_a_two': 20, 
            'X_b_one': 10,
            'X_b_two': 20, 
            'Y_a_one': 10,
            'Y_a_two': 20,
            'Y_b_one': 10,
            'Y_b_two': 20}
    nested = {'X': {'a': {'one': 10,
                          'two': 20}, 
                    'b': {'one': 10,
                          'two': 20}}, 
              'Y': {'a': {'one': 10,
                          'two': 20},
                    'b': {'one': 10,
                          'two': 20}}}
    print(nest_dict(flat) == nested)
    # True
    

提交回复
热议问题