Converting list to nested dictionary

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

提交回复
热议问题