Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.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_Algorithm_Recursion_Data Structures - Fatal编程技术网

动态重命名python嵌套字典中的键

动态重命名python嵌套字典中的键,python,python-3.x,algorithm,recursion,data-structures,Python,Python 3.x,Algorithm,Recursion,Data Structures,我需要动态地将以“@”开头的键重命名为不带“@”的键,无论它位于嵌套目录中的何处。示例输入目录: { '@personal_infonmation':{ 'name' : { '@first_name': 'Ashutosh', '@last_name' : 'Gupta' }, 'address':[{'@city': 'Mumbai'}, {'@city': 'Delhi'}] }

我需要动态地将以“@”开头的键重命名为不带“@”的键,无论它位于嵌套目录中的何处。示例输入目录:

{
    '@personal_infonmation':{
        'name' : {
            '@first_name': 'Ashutosh',
            '@last_name' : 'Gupta'
        },
        'address':[{'@city': 'Mumbai'}, {'@city': 'Delhi'}]
    }
}
输出

{
'personal_infonmation':{
    'name' : {
        'first_name': 'Ashutosh',
        'last_name' : 'Gupta'
    },
    'address':[{'city': 'Mumbai'}, {'city': 'Delhi'}]
}}
已尝试解决方案,但在所有情况下都无法正常工作:

def rename_keys(data):
    for k, v in data.items():
        if isinstance(v, dict):
            rename_keys(v)
        if isinstance(v, list):
            [rename_keys(row) for row in v]
        if k[0] == '@':
            data[k[1:]] = v
            data.pop(k)
失败案例:

{'@contentUrl': 'contentUrl', '@createdAt': '2020-06-11T09:08:13Z', '@defaultViewId': 'defaultViewId', '@encryptExtracts': 'false', '@id': 'id', '@name': 'Login', '@showTabs': 'true', '@size': '1', '@updatedAt': '2020-07-20T06:41:34Z', '@webpageUrl': 'webpageUrl', 'dataAccelerationConfig': {'@accelerationEnabled': 'false'}, 'owner': {'@id': 'id', '@name': 'name'}, 'project': {'@id': 'id', '@name': 'name'}, 'tags': {'tag': {'@label': 'label'}}, 'views': {'view': [{'@contentUrl': 'contentUrl', '@createdAt': '2020-06-11T09:08:13Z', '@id': 'id', '@name': 'name', '@updatedAt': '2020-07-20T06:41:34Z', '@viewUrlName': 'Sheet1', 'tags': {'tag': {'@label': 'label'}}}, {'@contentUrl': 'contentUrl', '@createdAt': '2020-06-11T09:08:13Z', '@id': 'id', '@name': 'name', '@updatedAt': 'updatedAt', '@viewUrlName': 'viewUrlName', 'tags': {'tag': {'@label': 'label'}}}]}}

问题是您在迭代字典时正在修改字典,下面是一个小演示:

data = {i: str(i) for i in range(8)}

for k,v in data.items():
    if k%3 != 0:
        del data[k]
        data[k+10] = "hello"
print(data)
数据应该只有可以被3整除的键,但是
5
显示不正确,解决方法是复制
.items()
的副本,以便在迭代时保留它,使循环如下所示:

for k,v in list(data.items()):

这应该可以解决问题。

我不认为递归函数会太难,你尝试过什么?@Tadhgmandald Jensen,我已经添加了我尝试过的解决方案,但它在所有情况下都不起作用。它在你发布的案例中都起作用,你想展示一个它不起作用的案例吗?我假设有一个非词典的列表。@Tadhgmdonald Jensen,也添加了失败的案例。工作很顺利,你能详细说明添加列表()的真正帮助吗?