【问题标题】:How can I recursively modify the keys and values of a nested dictionary?如何递归修改嵌套字典的键和值?
【发布时间】:2021-04-10 06:55:48
【问题描述】:

所以我有一个与此类似的任意深度的嵌套字典:

sample_dict = {
    'root_node': {
        'child_1': {
            'child_1a': {
                'child_1a_a': {},
                'child_1a_b': {},
                ...,
                'child_1a_x': {}
            },
            'child_1b': {
                'child_1b_a': {
                    'child_1b_a_a': {},
                    'child_1b_a_b': {},
                    ...
                },
                'child_1b_b': {
                    'child_1b_b_a': {},
                    ...
                },
                'child_1b_c': {}
            }
        },
        'child_2': {
                ...
            }
        }
    }

我需要把上面的字典转换成这样的:

sample_dict_output = {
    'title':'root_node',
    'key':'root_node',
    'children':[
        { 'title':'child_1',
          'key':'child_1',
          'children':[
              {'title':'child_1a',
               'key':'child_1a',
               'children':[
                 {'title': 'child_1a_a',
                  'key': 'child_1a_a'},
                 {'title': 'child_1a_b',
                  'key': 'child_1a_b'},
                   ...
                 {'title': 'child_1a_x',
                  'key': 'child_1a_x'},
               ],},
              {'title':'child_1b',
               'key':'child_1b',
               'children':[
                 {'title': 'child_1b_a',
                  'key': 'child_1b_a',
                  'children':[
                      {'title': 'child_1b_a_a',
                       'key': 'child_1b_a_a'},
                      {'title': 'child_1b_a_b',
                       'key': 'child_1b_a_b'},
                      ...
                  ],},
                 {'title': 'child_1b_b',
                  'key': 'child_1b_b',
                   'children':[
                    {'title': 'child_1b_b_a',
                     'key': 'child_1b_b_a'},
                    ...,
                 ],},
                {'title': 'child_1b_c',
                 'key': 'child_1b_c'}
                ],
              },
        { 'title':'child_2',
          'key':'child_2',
          'children':[...]
        }
    ],
}

我尝试在 Stackoverflow 中搜索解决方案并尝试递归,但无济于事。因此,任何帮助将不胜感激(最好在 Python 3.x 中)。谢谢!

【问题讨论】:

  • 你应该导航到字典,但这不一定是递归的。
  • 你能不能开始用英文描述一下输出和输入之间的关系是什么? “...转换成这样的东西。”真的吗?
  • 如果最外面的字典不是单例怎么办?整个输出不应该是一个列表吗?

标签: python python-3.x dictionary recursion nested


【解决方案1】:

以下内容将引导您走向正确的方向:

def convert_item(key, val):
    conv = {
        "title": key, 
        "key": key, 
    }
    if val:
        conv["children"] = convert_dict(val)
    return conv

def convert_dict(dct):
    return [
        convert_item(k, v) for k, v in dct.items()
    ]

>>> convert_dict(sample_dict)[0]
{
    "title": "root_node",
    "key": "root_node",
    "children": [
        {
            "title": "child_1",
            "key": "child_1",
            "children": [
                {
                    "title": "child_1a",
                    "key": "child_1a",
                    "children": [
                        {"title": "child_1a_a", "key": "child_1a_a"},
                        {"title": "child_1a_b", "key": "child_1a_b"},
                        {"title": "child_1a_x", "key": "child_1a_x"},
                    ],
                },
                {
                    "title": "child_1b",
                    "key": "child_1b",
                    "children": [
                        {
                            "title": "child_1b_a",
                            "key": "child_1b_a",
                            "children": [
                                {"title": "child_1b_a_a", "key": "child_1b_a_a"},
                                {"title": "child_1b_a_b", "key": "child_1b_a_b"},
                            ],
                        },
                        {
                            "title": "child_1b_b",
                            "key": "child_1b_b",
                            "children": [
                                {"title": "child_1b_b_a", "key": "child_1b_b_a"}
                            ],
                        },
                        {"title": "child_1b_c", "key": "child_1b_c"},
                    ],
                },
            ],
        }
    ],
}

或者使用单个递归函数:

def convert_dict(dct):
    return [
        {"title": k, "key": k, **({"children": convert_dict(v)} if v else {})}
        for k, v in dct.items()
    ]

【讨论】:

  • 不,不是。这只是为了方便和可读性,您可以轻松地将其转换为单个函数。
  • 唯一可能出现的问题是您的数据是否偏离给定的结构或包含一个圆圈(其中的任何 dict 都包含自己作为(嵌套)值)。但这会使任何幼稚的实现无限递归。
  • ** 解压缩它应用到的字典。这是在包含“children”键的潜在空字典中展平的技巧。
  • 这与双功能变体完全相同。仅当有子项(非空 val)时才插入子项。
猜你喜欢
  • 2018-07-10
  • 1970-01-01
  • 2018-09-13
  • 2021-12-16
  • 2022-01-15
  • 2018-10-08
  • 2019-07-18
  • 1970-01-01
  • 2015-01-02
相关资源
最近更新 更多