使用键字典重新配置嵌套字典键名称

问题描述 投票:0回答:1

我需要根据键字典更新嵌套字典中的键。这涉及比较两个字典中的键。如果某个键匹配,我需要在嵌套字典中搜索该键下的所有元素,并根据键字典更新它们的名称。

Key_dict
也是嵌套字典。用我的代码清空
dict
,任何支持将不胜感激。

old_Dict =
{'candela_samples_generic': {'drc_dtcs': {'domain_name': 'TEMPLATE-DOMAIN', 'dtc_all': {'0x930001': {'identification': {'code': '0x9300', 'fault_type': '0x11', 'description': 'GNSS antenna short to ground'}, 'snapshots': {'snapshot_record_content': 'base', 'snapshot_records_numbers': ['0x01']}, 'functional_conditions': {'failure_name': 'short_to_ground', 'mnemonic': 'DTC_GNSS_Antenna_Short_to_ground'}}}}}}`

key_dict= {
    'dtc_all': {
        'code': 'udsDtcValue',
        'failure_name': 'failname',
        'mnemonic' : 'LongName',
         'fault_type': 'FaultType',
         'snapshot_records_numbers': 'snapshotrecordsnumbers'
    }
}
def replace_keys(old_dict, key_dict):
    new_dict = {}

    if isinstance(old_dict, dict):
        for key, value in old_dict.items():
            if key == "dtc_all":
                for key in key.keys():
                    new_key = key_dict.get(key, key)
                    if isinstance(old_dict[key], dict):
                        new_dict[new_key] = replace_keys(old_dict[key], key_dict)
                    else:
                        new_dict[new_key] = old_dict[key]
        return new_dict
Output:
new_Dict =
{'candela_samples_generic': {'drc_dtcs': {'domain_name': 'TEMPLATE-DOMAIN', 'dtc_all': {'0x930001': {'identification': {'udsDtcValue': '0x9300', 'FaultType': '0x11', 'description': 'GNSS antenna short to ground'}, 'snapshots': {'snapshot_record_content': 'base', 'snapshotrecordsnumbers': ['0x01']}, 'functional_conditions': {'failname': 'short_to_ground', 'LongName': 'DTC_GNSS_Antenna_Short_to_ground'}}}}}}`

想要使该函数通用,以便它可以处理

key_dict
中的多个键,根据
old_dict
中对应的键更新
key_dict
的特定键下的元素。

python dictionary nested rename
1个回答
0
投票

让我们看看...🤔 无需在每个递归级别创建并返回多个字典, 您需要根据映射就地替换字典键:

def replace_keys_in_place(old_dict, key_dict):
    def replace_keys_recursive(current_dict, key_mapping):
        for old_key in list(current_dict.keys()):
            if old_key in key_mapping:
                new_key = key_mapping[old_key] if isinstance(key_mapping[old_key], str) else old_key
                if new_key != old_key:
                    current_dict[new_key] = current_dict.pop(old_key)
                if isinstance(current_dict[new_key], dict):
                    replace_keys_recursive(current_dict[new_key], key_mapping.get(old_key, key_mapping))
            elif isinstance(current_dict[old_key], dict):
                replace_keys_recursive(current_dict[old_key], key_mapping)
    replace_keys_recursive(old_dict, key_dict) 
    return old_dict

如果有效,请不要忘记标记为正确并点赞😊

© www.soinside.com 2019 - 2024. All rights reserved.