Python 编写go_back函数实现分组字典b_dict反向还原
Python字典分组反向还原实现
问题说明
- 已完成正向分组逻辑:实现函数
fun_dict,将原字典中值相同的键归为一组,生成以原字典值为键、同值键列表为值的分组字典b_dict - 待实现反向转换函数
go_back:将分组后的b_dict还原为与原字典结构完全等价的字典,当前直接复用fun_dict处理b_dict无法得到正确结果
现有代码框架
a_dict = {'A': 1, 'B': 2, 'C': 3, 'D': 1, 'E': 2, 'F': 3} print('a_dict: ', a_dict) def fun_dict(a_dict): b_dict = {} for i, v in a_dict.items(): b_dict[v] = [i] if v not in b_dict.keys() else b_dict[v] + [i] return b_dict def go_back(b_dict): # # Need a function to convert b_dict to c_dict to go back as the expected output # b_dict = fun_dict(a_dict) print('Grouped dict: ', b_dict) c_dict = fun_dict(b_dict) print('Went to the original dict: ', c_dict)
预期输出
- 原始
a_dict:{'A': 1, 'B': 2, 'C': 3, 'D': 1, 'E': 2, 'F': 3} - 分组后的
b_dict:{1: ['A', 'D'], 2: ['B', 'E'], 3: ['C', 'F']} - 经
go_back转换后的c_dict:{'A': 1, 'D': 1, 'B': 2, 'E': 2, 'C': 3, 'F': 3},与原始a_dict结构等价
反向转换实现方案
核心逻辑
- 遍历
b_dict的每一项:项的键是原字典存储的标量值(如1、2、3),项的值是所有持有该标量值的原字典键组成的列表 - 逐一取出列表中的原字典键,将其作为新字典的键,对应分组的标量值作为新字典的值,组装完成后即为还原的目标字典
实现代码
def go_back(b_dict): c_dict = {} for group_val, ori_keys in b_dict.items(): for ori_key in ori_keys: c_dict[ori_key] = group_val return c_dict
注:直接复用fun_dict处理b_dict无效的原因:fun_dict的适配场景是值为标量的普通字典,b_dict的值为列表类型,直接套用归堆逻辑会将列表作为整体值分组,完全无法匹配原字典结构。
内容的提问来源于stack exchange,提问作者user10894226
相关产品推荐
相关产品推荐

