0

任何人都可以帮助我..我有数据列表

namelist=['res/anim/satu.jpg','res/anim/dua.jpg','res/draw/logo.jpg','res/draw/img/bg.png','res/draw/img/fg.png']

如何像这样转换为dict

{'res': {'anim':['satu.jpg', 'dua.jpg']},'draw': ['logo.jpg', {'img':['bg.jpg', 'fg.jpg']}]}
4

1 回答 1

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']}}

但你真的想重新考虑你的结构策略。否则,您必须在列表中搜索映射(在异常处理程序中)。

于 2013-06-09T16:46:13.133 回答