How can I split a string and form a multi-level nested dictionary?

前端 未结 2 1154
野趣味
野趣味 2020-12-19 02:59

I have a string like

foo/bar/baz

I also have val=1 for example. Is there a clean way to split the foo/bar/baz int

2条回答
  •  [愿得一人]
    2020-12-19 03:17

    d = 1
    for part in reversed(s.split('/')):
        d = {part: d}
    

    If this needs to be extended to create something like a directory tree, you might want a solution based on defaultdict:

    import collections
    
    def tree():
        return collections.defaultdict(tree)
    
    def parsetree(path_strings):
        t = tree()
        for s in path_strings:
            temp = t
            parts = s.split('/')
            for part in parts[:-1]:
                temp = temp[part]
            temp[parts[-1]] = 1
        return t
    

    Demo:

    >>> t = parsetree([
    ...     'foo/bar/baz',
    ...     'foo/bar/bop',
    ...     'foo/spam'
    ... ])
    >>> t['foo']['bar']['baz']
    1
    >>> t['foo']['spam']
    1
    

提交回复
热议问题