根据值的数量串联嵌套字典键

2024-10-03 21:36:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试操作嵌套字典,以便将任何嵌套字典的键向后组合到只有一个键的情况下。你知道吗

我曾经尝试递归地这样做,但是我很难从字典中删除键并用串联键替换它们。你知道吗

例如:

{'adv':
    {'e':
        {'r':
            {
                's':
                    {'e':
                         {'_end_': '_end_'}
                     },
                't':
                    {'_end_': '_end_',
                     'i':
                         {'s':
                              {'e':
                                   {'r':
                                        {'_end_': '_end_'}
                                    }
                               }
                          }
                     }
            }
        },
        'i': {'c': {'e': {'_end_': '_end_'}
                    }
              }
    }
}

会变成

{'adv':
    {'er':
        {
            'se':
                {'_end_': '_end_'},
        't':
            {'_end_': '_end_',
             'iser':
                 {'_end_': '_end_'}

             }
        },
        'ice':
                 {'_end_': '_end_'}
    }
}

Tags: 字典情况enderseiceadviser
1条回答
网友
1楼 · 发布于 2024-10-03 21:36:33

这是一个有趣的问题-可能有一个更优雅的解决方案,但我做到了以下几点:

import pprint

t={'adv': {'e': {'r': {'s': {'e': {'_end_': '_end_'}},
                       't': {'_end_': '_end_',
                             'i': {'s': {'e': {'r': {'_end_': '_end_'}}}}}}},
           'i': {'c': {'e': {'_end_': '_end_'}}}}}


def concat_dict(d):
    if d == '_end_':
        return '_end_'

    rv = {}

    for k, v in d.items():
        if '_end_' in v:
            rv[k] = concat_dict(v)
        elif len(list(x for x in v.keys() if x != '_end_')) == 1:
            top_str = k
            next_str = list(v.keys())[0]
            rv[top_str + next_str] = concat_dict(v[next_str])
        else:
            rv[k] = concat_dict(v)
    return rv

def format_dict(d):
    while concat_dict(d) != d:
        d = concat_dict(d)
    return d


pprint.pprint(format_dict(t))

输出:

{'adv': {'er': {'se': {'_end_': '_end_'},
                't': {'_end_': '_end_', 'iser': {'_end_': '_end_'}}},
         'ice': {'_end_': '_end_'}}}

相关问题 更多 >