Creating a nested dictionary from a flattened dictionary

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

    output = {}
    
    for k, v in source.items():
        # always start at the root.
        current = output
    
        # This is the part you're struggling with.
        pieces = k.split('_')
    
        # iterate from the beginning until the second to last place
        for piece in pieces[:-1]:
           if not piece in current:
              # if a dict doesn't exist at an index, then create one
              current[piece] = {}
    
           # as you walk into the structure, update your current location
           current = current[piece]
    
        # The reason you're using the second to last is because the last place
        # represents the place you're actually storing the item
        current[pieces[-1]] = v
    

提交回复
热议问题