我有一个严格排序的字符串列表:
['a',
'b',
'b/c',
'b/d',
'e',
'f',
'f/g',
'f/h',
'f/h/i',
'f/h/i/j']
此列表类似于树表示。所以,我需要将它转换为dict:
{'a': {},
'b': {'c': {},
'd': {}},
'e': {},
'f': {'g': {},
'h': {'i': {'j': {}}}}}
正如你所看到的,这个词典中的键是父母,而值是孩子。
UPD:我同意空字典优于无
答案 0 :(得分:8)
如果您不坚持使用None
作为叶值,则可以使用紧凑代码
my_dict = lambda: defaultdict(my_dict)
d = my_dict()
for x in my_list:
reduce(defaultdict.__getitem__, x.split("/"), d)
不可否认, 显然不是这个代码的作用,但它很简洁:)
答案 1 :(得分:5)
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
请注意,元素不会按字母顺序存储在字典中!
答案 2 :(得分:0)
这是我对它的抨击。我颠倒了优化路径,因为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'])
答案 3 :(得分:0)
希望它有所帮助,递归方法:)
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)
答案 4 :(得分:0)
这是我的决议:
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))