Creating a nested dictionary from a flattened dictionary

后端 未结 7 2050
-上瘾入骨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:13

    Here is a reasonably readable recursive result:

    def unflatten_dict(a, result=None, sep='_'):
    
        if result is None:
            result = dict()
    
        for k, v in a.items():
            k, *rest = k.split(sep, 1)
            if rest:
                unflatten_dict({rest[0]: v}, result.setdefault(k, {}), sep=sep)
            else:
                result[k] = v
    
        return result
    
    
    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}
    
    print(unflatten_dict(flat))
    {'X': {'a': {'one': 10, 'two': 20}, 'b': {'one': 10, 'two': 20}}, 
     'Y': {'a': {'one': 10, 'two': 20}, 'b': {'one': 10, 'two': 20}}}
    

    This is based on a couple of the above answers, uses no imports and is only tested in python 3.

提交回复
热议问题