4

I have a string that could be different lengths, and I want to create a nested dictionary. I have this so far, and just cant seem to figure out how to get over the variable depth issue.

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

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

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

Would love some feedback on design and ideas to get this going.

Thanks,

5 Answers 5

3

Just update the loop as follows:

y = {}
for item in reversed(x):
    y = {item: y}
Sign up to request clarification or add additional context in comments.

Comments

2

One Line Reduce version of @ozgur's 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 Comments

I preferred your first answer that you deleted. Relying on reversed() can be problematic if you end up having to deal with iterators/generators but that is outside the scope of OPs question.
@AChampion The reversed one seems so simple though. But that's a good point, although rare, there could be a generator or iterator that you want to step through
0

Try this:

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

Output:

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

Comments

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

1 Comment

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
0

One simple way of doing this is recursion:

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': {}}}}}

But if you want to do it iteratively then you are very close, just use a cursor to walk down the structure:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.