Python中按条件更新嵌套字典自定义类键并保留嵌套结构的方法
解决方案
首先修正你当前CompWord类__eq__方法的逻辑问题:原有实现直接拿self.c和other比较,当other为CompWord实例时会出现匹配错误,修改如下:
from dataclasses import dataclass from collections import defaultdict @dataclass class CompWord: c: str length: int def __hash__(self): return hash(self.c) def __eq__(self, other): # 先判断类型,再比较c属性,保证匹配逻辑正确 if isinstance(other, CompWord): return self.c == other.c return False
Python字典的键本身不支持直接修改,你可以通过「取出旧键对应值→删除旧键→插入新键+旧值」的流程完成更新,同时完整保留所有嵌套内容。具体实现代码如下:
def update_comp_key(target_dict: defaultdict, new_key: CompWord) -> None: # 先判断对应c属性的键是否存在 if new_key not in target_dict: # 不存在时可按需添加插入逻辑,这里直接返回 return # 遍历找到匹配的旧键 old_key = None for k in target_dict.keys(): if k == new_key: old_key = k break # 仅当新键的length大于旧键时执行更新 if new_key.length > old_key.length: # 取出旧值,完整保留所有嵌套内容 old_value = target_dict.pop(old_key) # 插入新键和旧值完成替换 target_dict[new_key] = old_value
使用示例
# 初始化你原来的嵌套字典 _ = lambda: defaultdict(_) d = _() for compword1 in [CompWord('a', 1), CompWord('b', 2)]: key = d[compword1] for compword2 in [CompWord('c', 1), CompWord('d', 2)]: key = key[compword2] # 测试更新逻辑 c_word = CompWord('a', 4) update_comp_key(d, c_word)
运行后打印字典键即可看到,原CompWord(c='a', length=1)已被替换为CompWord(c='a', length=4),下层嵌套的所有字典内容完全保留。如果需要更新嵌套层级的键,只需把对应内层字典作为第一个参数传入update_comp_key即可。
内容的提问来源于stack exchange,提问作者onesiumus
相关产品推荐
相关产品推荐

