You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于另一个字典的键值对替换目标字典中的键?

问题描述

我拥有两个字典:

Dict1 = {'M0': 399, 'M1': 71, 'M2': '0.979827269', 'M3': '0.84576281', 'M4': '0.011849132', 'M5': '0.066588785'}
Dict2 = {'M0': 'KPI1', 'M1': 'KPI2', 'M2': 'KPI3', 'M3': 'KPI4', 'M4': 'KPI5', 'M5': 'KPI6'}

希望基于Dict2的键值对更新Dict1的键,最终得到如下字典:

{'KPI1': 399, 'KPI2': 71, 'KPI3': '0.979827269', 'KPI4': '0.84576281', 'KPI5': '0.011849132', 'M5': '0.066588785'}

解决方案

方式1:遍历指定替换(推荐)

通过遍历Dict1的键值对,按需选择替换或保留原键,逻辑清晰易维护:

# 定义无需替换的键集合
keep_original = {'M5'}
updated_dict = {}

for key, val in Dict1.items():
    if key in keep_original:
        updated_dict[key] = val
    else:
        updated_dict[Dict2[key]] = val

方式2:全替换后恢复指定键

先按Dict2全量替换所有键,再将需要保留的键恢复:

# 全量替换键
updated_dict = {Dict2[k]: v for k, v in Dict1.items()}
# 恢复M5的原键,同时移除替换后的KPI6键
updated_dict['M5'] = updated_dict.pop('KPI6')

两种方式运行后都能得到目标字典,可根据实际场景选择。

内容的提问来源于stack exchange,提问作者z star

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 20:06:28