Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何递归地修改嵌套字典的键和值?_Python_Python 3.x_Dictionary_Recursion_Nested - Fatal编程技术网

Python 如何递归地修改嵌套字典的键和值?

Python 如何递归地修改嵌套字典的键和值?,python,python-3.x,dictionary,recursion,nested,Python,Python 3.x,Dictionary,Recursion,Nested,因此,我有一个任意深度的嵌套字典,类似于: sample_dict = { 'root_node': { 'child_1': { 'child_1a': { 'child_1a_a': {}, 'child_1a_b': {}, ..., 'child_1a_x': {} },

因此,我有一个任意深度的嵌套字典,类似于:

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中搜索解决方案,并尝试递归,但没有成功。因此,任何帮助都将不胜感激(最好是在Python3.x中)。谢谢大家!

以下内容将为您指明正确的方向:

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不是一个单体呢?整件事不应该是一张单子吗?不,不是真的。这只是为了方便和可读性,您可以轻松地将其转换为单个函数。唯一可能出现的问题是,如果您的数据偏离给定的结构或包含一个圆(其中的任何dict本身包含一个(嵌套)值)。但这会使任何幼稚的实现无限递归。
**
解压它所应用的字典。这是一个在包含“children”键的可能为空的dict中展平的技巧。这与两个函数变量的作用完全相同。仅当存在子项(非空val)时才插入子项键。