简体   繁体   English

从列表构建嵌套的python字典

[英]Building a nested python Dictionary from list

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 One Line Reduce版本@ ozgur的答案

>>> 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 但我更喜欢@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': {}}}}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM