Creating a nested python dictionary from a list

I have a string that can be of different lengths and I want to create a nested dictionary. I still have it, and I just can’t figure out how to overcome the problem with variable depth.

    string = "a/b/c/b"
    x = string.split('/')
    y = {}
    for item in x:
      y[item] = dict()
      .............

I tried many different ways, but just don’t know how to build it dynamically. The end result that I would like to get is:

{'a' :{'b' : {'c': {'d': {}}}}

I would like some feedback on design and ideas to achieve this.

Thank,

+4
source share
5 answers

Just update the loop like this:

y = {}
for item in reversed(x):
    y = {item: y}
+3
source

One line downgrade @ozgur answer

>>> string = "a/b/c/d"
>>> reduce(lambda x, y: {y: x}, reversed(string.split('/')), {})
{'a': {'b': {'c': {'d': {}}}}}

But I prefer the original answer from @ozgur

+2

:

string = "a/b/c/b"
x = string.split('/')
x.reverse()
y = {}
count=0
for item in x:
    if count==0:
        tmp={item:{}}
    else:
        tmp={item: tmp}
    count+=1
print tmp

:

{'a': {'b': {'c': {'b': {}}}}}
0

- :

def fn(s):
    if not s:
        return {}
    x, *y = s   # Python3, for Python2 x, y = s[0], s[1:]
    return {x:fn(y)}

>>> fn("a/b/c/b".split('/'))
{'a': {'b': {'c': {'b': {}}}}}

, , , :

>>> y = {}
>>> c = y
>>> for item in "a/b/c/b".split('/'):
...     c[item] = {}
...     c = c[item]
>>> y
{'a': {'b': {'c': {'b': {}}}}}
0
>>> text = 'a/b/c/d'
>>> d = node = {}
>>> for c in text.split('/'):
...   node = node.setdefault(c, {})
... 
>>> d
{'a': {'b': {'c': {'d': {}}}}}
0

Source: https://habr.com/ru/post/1672516/


All Articles