Converting list to nested dictionary

后端 未结 4 1184
花落未央
花落未央 2021-01-18 08:50

How can I convert a list into nested `dictionary\'?

For example:

l = [1, 2, 3, 4] 

I\'d like to convert it to a dictio

4条回答
  •  一生所求
    2021-01-18 09:25

    Here is an abstraction. Uses for setdefault are typically overshadowed by defaultdict, but here is an interesting application if you have one or more lists (iterables):

    def make_nested_dict(*iterables):
        """Return a nested dictionary."""
        d = {}
        for it in iterables:
            temp = d
            for i in it:
                temp = temp.setdefault(i, {})
        return d
    
    make_nested_dict([1, 2, 3, 4])
    # {1: {2: {3: {4: {}}}}}
    
    make_nested_dict([1, 2, 3, 4], [5, 6])
    # {1: {2: {3: {4: {}}}}, 5: {6: {}}}
    

    Nested Branches

    Unlike defaultdict, this technique accepts duplicate keys by appending to existing "branches". For example, we will append a new 7 → 8 branch at the third level of the first (A) branch:

                           A         B           C            
    make_nested_dict([1, 2, 3, 4], [5, 6], [1, 2, 7, 8])
    # {1: {2: {3: {4: {}}, 7: {8: {}}}}, 5: {6: {}}}
    

    Visually:

    1 → 2 → 3 → 4   (A)            5 → 6   (B)
           \ 
            7 → 8   (C)
    

提交回复
热议问题