任何人都可以帮助我.. 我有数据清单
namelist=['res/anim/satu.jpg','res/anim/dua.jpg','res/draw/logo.jpg','res/draw/img/bg.png','res/draw/img/fg.png']
如何转换为像这样的词典
{'res': {'anim':['satu.jpg', 'dua.jpg']},'draw': ['logo.jpg', {'img':['bg.jpg', 'fg.jpg']}]}
答案 0 :(得分:0)
简单地构建结构:
result = {}
for name in namelist:
parts = name.split('/')
target = result
for part in parts[:-2]:
try:
target = target.setdefault(part, {})
except AttributeError: # hit list leaf, add dictionary
try:
target = next(t for t in target if isinstance(t, dict))
except StopIteration:
target.append({})
target = target[-1]
try:
target.setdefault(parts[-2], []).append(parts[-1])
except AttributeError: # hit list leaf, add dictionary
try:
target = next(t for t in target if isinstance(t, dict))
target.setdefault(parts[-2], []).append(parts[-1])
except StopIteration:
target.append({parts[-2]: [parts[-1]]})
这给出了:
{'res': {'draw': ['logo.jpg', {'img': ['bg.png', 'fg.png']}], 'anim': ['satu.jpg', 'dua.jpg']}}
但你真的想重新思考你的结构策略。您必须在列表中搜索映射(在异常处理程序中)。否则。