用映射字典更改字典的键 [英] Change keys of a dict with a mapping dict

查看:94
本文介绍了用映射字典更改字典的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过将映射字典传递给也替换嵌套键的函数来替换字典的键名. 问题是我在嵌套字典中有多个名为"id"的键,并且我想用特定名称重命名这些"​​id".

I want to replace keys name of a dictionary by passing a mapping dict with a function that replace also nested keys. The issue is that I have multiple keys named 'id' in nested dictionary and I want to rename these 'id' with specific names.

初始词典:

initial_dict = {'id': 1, 'netAmount': 10.2, 'modifiedOn': '2017-01-01',
                    'statusId': 3, 'approvalStateId': 3, 'approvalState': {'id': 3,'name':'Approved'}}

映射字典:

 mapping_dict = {'id': 'pr_id', 'netAmount': 'net_amount', 'modifiedOn': 'modified_date',
                'statusId': 'status_id', 'approvalStateId': 'approval_id','approvalState':{'id':'approv_id'}}

所需的字典输出:

    output_dict = {'pr_id': 1, 'net_amount': 10.2, 'modified_date': '2017-01-01',
                    'status_id': 3, 'approval_id': 3, 'approvalState': {'approv_id': 3, 'name': 'Approved'}}

我是这样做的,但是它只替换了字典第一级的键,如果我尝试在映射字典中设置嵌套键,则会出现错误.

What I did is this but it only replace keys of the first level of the dict and if I try to set nested keys in the mapping dict, I get an error.

def map_fields(obj):
    new_obj = {}
    mapping_dict = {'id': 'pr_id', 'netAmount': 'net_amount', 'modifiedOn': 'modified_date',
                    'statusId': 'status_id', 'approvalStateId': 'approval_id','approvalState':{'id':'approv_id'}}
    for key in obj.keys():
        if key in mapping_dict:
            new_key = mapping_dict[key]
        else:
            new_key = key
        new_obj[new_key] = obj[key]
    return new_obj

你知道怎么做吗?

谢谢

推荐答案

您需要一个递归函数才能逐步完成嵌套字典.关键是递归时,您需要同时传递子词典和子映射词典.

You need a recursive function to be able to step up through the nested dictionaries. The key is that when recursing, you need to pass both the child dictionary, and the child mapping dictionary.

请注意,映射字典的结构特定于此问题,并且不允许您更改嵌套字典的键-您需要重组存储映射的方式以实现此目的.

Note that the structure of your mapping dict is specific to this problem, and doesn't allow you to change the key of a nested dictionary - you'd need to restructure how you store the mapping to achieve that.

以下内容应做您想要的(添加打印语句以帮助其在运行时遵循逻辑):

The following should do what you want (print statements added to help follow the logic when it runs):

def map_fields(init_dict, map_dict, res_dict=None):

    res_dict = res_dict or {}
    for k, v in init_dict.items():
        print("Key: ", k)
        if isinstance(v, dict):
            print("value is a dict - recursing")
            v = map_fields(v, map_dict[k])
        elif k in map_dict.keys():
            print("Remapping:", k, str(map_dict[k]))
            k = str(map_dict[k])
        res_dict[k] = v
    return res_dict

print(map_fields(initial_dict, mapping_dict))

这篇关于用映射字典更改字典的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆