Converting list to nested dictionary

后端 未结 4 1183
花落未央
花落未央 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: {}}}}}
    

提交回复
热议问题