Converting list to nested dictionary

后端 未结 4 1182
花落未央
花落未央 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:15

    For that reverse the list, then start creating the empty dictionary element.

    l = [1, 2, 3, 4]
    d = {}
    for i in reversed(l):
        d = {i: d}
    
    >>> print(d)
    {1: {2: {3: {4: {}}}}}
    
    0 讨论(0)
  • 2021-01-18 09:19

    You could also use functools.reduce for this.

    reduce(lambda cur, k: {k: cur}, reversed(l), {})
    

    Demo

    >>> from functools import reduce
    >>> l = [1, 2, 3, 4]
    
    >>> reduce(lambda cur, k: {k: cur}, reversed(l), {})
    {1: {2: {3: {4: {}}}}}
    

    The flow of construction looks something like

    {4: {}} -> {3: {4: {}} -> {2: {3: {4: {}}}} -> {1: {2: {3: {4: {}}}}}

    as reduce traverses the reverse iterator making a new single-element dict.

    0 讨论(0)
  • 2021-01-18 09:24

    You can do something like this:

    l = [1,2,3,4]
    d = {}
    
    for i in l[::-1]:
        d = {i: d}
    
    print(d)
    

    {1: {2: {3: {4: {}}}}} [Finished in 0.4s]

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题