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

Python中如何按键映射合并字典,将数字键替换为对应字母键?

字典键值映射合并问题解决方法

原字典与需求

现有两个字典:

dict1 = {4: [741, 114, 306, 70],
         2: [77, 325, 505, 144],
         3: [937, 339, 612, 100],
         1: [52, 811, 1593, 350]}
dict2 = {1: 'A', 2: 'B', 3: 'C', 4: 'D'}

需要将dict2的value作为新字典的key,对应dict1中相同原key的value,期望输出:

output = {'D': [741, 114, 306, 70],
          'B': [77, 325, 505, 144],
          'C': [937, 339, 612, 100],
          'A': [52, 811, 1593, 350]}

原代码问题分析

你提供的代码错误在于:

  1. 使用{**dict1, **dict2}合并时,相同key会被dict2覆盖,保留的是原数字键而非目标字母键
  2. 循环中仅修改了原键对应的值为[dict2值, dict1值]的列表结构,完全没有替换键为dict2的字母,不符合需求

正确解法

方法一:字典推导式(最简洁)

output = {dict2[key]: dict1[key] for key in dict1}

遍历dict1的每个key,用dict2[key]作为新字典的键,直接映射dict1对应的值。

方法二:循环构建字典

def merge_dictionaries(dict1, dict2):
    result = {}
    for key, value in dict1.items():
        result[dict2[key]] = value
    return result

output = merge_dictionaries(dict1, dict2)

初始化空字典,逐个将dict2的value作为新键,把dict1的对应值赋值给新键。

两种方法均能得到符合预期的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:05:30