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,
Just update the loop as follows:
y = {}
for item in reversed(x):
y = {item: y}
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
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': {}}}}}
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': {}}}}}
>>> text = 'a/b/c/d'
>>> d = node = {}
>>> for c in text.split('/'):
... node = node.setdefault(c, {})
...
>>> d
{'a': {'b': {'c': {'d': {}}}}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.