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: {}}}}}
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.
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.
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.
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.
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: {}}}}}
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With