Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting list to nested dictionary

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

For example:

l = [1, 2, 3, 4] 

I'd like to convert it to a dictionary that looks like this:

{1: {2: {3: {4: {}}}}}
like image 220
Chaitanya Pandit Avatar asked Mar 08 '17 17:03

Chaitanya Pandit


People also ask

How do I convert a nested list to a dictionary?

We can convert a nested list to a dictionary by using dictionary comprehension. It will iterate through the list. It will take the item at index 0 as key and index 1 as value.

How do you create a nested dictionary from a list Python?

To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.

How do I convert a list to a dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

How do I convert a list to a dictionary key?

To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.


3 Answers

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: {}}}}}
like image 157
Ankur Jyoti Phukan Avatar answered Oct 15 '22 14:10

Ankur Jyoti Phukan


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.

like image 22
miradulo Avatar answered Oct 15 '22 12:10

miradulo


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]

like image 40
Den1al Avatar answered Oct 15 '22 13:10

Den1al