如何将严格排序的字符串列表转换为字典?

发布于 2024-12-10 20:18:21 字数 372 浏览 0 评论 0原文

我有一个严格排序的字符串列表:

['a',
 'b',
 'b/c',
 'b/d',
 'e',
 'f',
 'f/g',
 'f/h',
 'f/h/i',
 'f/h/i/j']

该列表类似于树表示。因此,我需要将其转换为字典:

{'a': {},
 'b': {'c': {},
       'd': {}},
 'e': {},
 'f': {'g': {},
       'h': {'i': {'j': {}}}}}

如您所见,该字典中的键是父级,值是子级。

UPD:我同意空字典更好

I have a strictly sorted list of strings:

['a',
 'b',
 'b/c',
 'b/d',
 'e',
 'f',
 'f/g',
 'f/h',
 'f/h/i',
 'f/h/i/j']

This list is similar to tree representation. So, I need to convert it to dict:

{'a': {},
 'b': {'c': {},
       'd': {}},
 'e': {},
 'f': {'g': {},
       'h': {'i': {'j': {}}}}}

As you can see, keys in this dict are parents and values are children.

UPD: I agree that empty dict is better than None

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

盗梦空间 2024-12-17 20:18:21

如果您不坚持使用 None 作为叶值,您可以使用紧凑的代码。

my_dict = lambda: defaultdict(my_dict)
d = my_dict()
for x in my_list:
    reduce(defaultdict.__getitem__, x.split("/"), d)

不可否认,这段代码的作用并不明显,但它很简洁: )

If you don't insist on None as the leaf value, you can use the compact code

my_dict = lambda: defaultdict(my_dict)
d = my_dict()
for x in my_list:
    reduce(defaultdict.__getitem__, x.split("/"), d)

Admittedly, it isn't that obvious what this code does, but it's succinct :)

手心的温暖 2024-12-17 20:18:21
di = {}
for a in arr:
    al = a.split("/")
    d = di
    for elem in al:
        if elem in d:
            d = d[elem]
        else:
            d[elem]={}

print di

请注意,元素不按字母顺序存储在字典中!

di = {}
for a in arr:
    al = a.split("/")
    d = di
    for elem in al:
        if elem in d:
            d = d[elem]
        else:
            d[elem]={}

print di

Note that elemts are not stored in alphabetical order in a dictionary!

攒一口袋星星 2024-12-17 20:18:21

希望它有帮助,递归方法:)

import pprint

l = ['a',
'b',
'b/c',
'b/d',
'e',
'f',
'f/g',
'f/h',
'f/h/i',
'f/h/i/j']

def put(d, elems):
    f = elems[0]
    if len(elems)==1:
        d[f]=None
    else:
        if f not in d or d[f]==None:
            d[f] = {}
        put(d[f], elems[1:])

d = {}
for x in l:
    put(d, x.split('/'))

pprint.pprint(d)

Hope it helps, recursive approach :)

import pprint

l = ['a',
'b',
'b/c',
'b/d',
'e',
'f',
'f/g',
'f/h',
'f/h/i',
'f/h/i/j']

def put(d, elems):
    f = elems[0]
    if len(elems)==1:
        d[f]=None
    else:
        if f not in d or d[f]==None:
            d[f] = {}
        put(d[f], elems[1:])

d = {}
for x in l:
    put(d, x.split('/'))

pprint.pprint(d)
不交电费瞎发啥光 2024-12-17 20:18:21

这是我的破解方法。我反转了优化路径,因为 pop() 比 pop(0) 快得多。

def add_branch(root, path):
    branch = path.pop()
    if path:
        if branch not in root or root[branch] is None:
            root[branch] = {}
        add_branch(root[branch], path)
    else:
        root[branch] = None

def totree(strings):
    root = {}
    for string in strings:
        path = string.split("/")
        path.reverse()
        add_branch(root, path)
    return root

像这样使用:

my_tree = totree(['a', 'b', 'b/c', 'b/d', 'e', 'f', 'f/g', 'f/h', 
    'f/h/i', 'f/h/i/j'])

Here's my crack at it. I reverse the path for optimization, because pop() is much faster than pop(0).

def add_branch(root, path):
    branch = path.pop()
    if path:
        if branch not in root or root[branch] is None:
            root[branch] = {}
        add_branch(root[branch], path)
    else:
        root[branch] = None

def totree(strings):
    root = {}
    for string in strings:
        path = string.split("/")
        path.reverse()
        add_branch(root, path)
    return root

Use like this:

my_tree = totree(['a', 'b', 'b/c', 'b/d', 'e', 'f', 'f/g', 'f/h', 
    'f/h/i', 'f/h/i/j'])
楠木可依 2024-12-17 20:18:21

这是我的决议:

from collections import defaultdict
from pprint import pprint

input = ['a', 'b', 'b/c', 'b/d', 'e', 'f', 'f/g', 'f/h', 'f/h/i', 'f/h/i/j']
result = defaultdict(dict)
for i in input:
    path = i.split('/')
    key = path[0]
    value = {}
    buffer = {key:value}
    for folder in path[1:]:
        value[folder] = {}
        value = value[folder]
    result[key].update(buffer[key])
pprint(dict(result))

this is my resolution:

from collections import defaultdict
from pprint import pprint

input = ['a', 'b', 'b/c', 'b/d', 'e', 'f', 'f/g', 'f/h', 'f/h/i', 'f/h/i/j']
result = defaultdict(dict)
for i in input:
    path = i.split('/')
    key = path[0]
    value = {}
    buffer = {key:value}
    for folder in path[1:]:
        value[folder] = {}
        value = value[folder]
    result[key].update(buffer[key])
pprint(dict(result))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文