Python中是否存在Pythonic的字典扩展方法可满足值保留与去重需求?
问题解答
1. 保留所有值的Pythonic合并方案
Python没有内置实现该合并逻辑的原生方法,但可以通过简化分支逻辑写出符合Pythonic规范的实现,无需大量冗余的类型判断:
def extend(d1: dict, d2: dict) -> dict: # 辅助函数:把任意值转为单层列表,避免修改原列表用copy def to_list(val): return val.copy() if isinstance(val, list) else [val] res = {} # 取两个字典的所有唯一键 all_keys = d1.keys() | d2.keys() for k in all_keys: if k not in d1: res[k] = d2[k] elif k not in d2: res[k] = d1[k] else: res[k] = to_list(d1[k]) + to_list(d2[k]) return res
测试效果匹配需求:
d1={'a':'a','b':'b','c':'c'} d2={'b':'a','c':['d','f','g'],'e':'e'} print(extend(d1, d2)) # 输出:{'a': 'a', 'b': ['b', 'a'], 'c': ['c', 'd', 'f', 'g'], 'e': 'e'}
2. 去重版本实现(补充提问解答)
调整需求为移除重复值时,仅需新增简单的有序去重逻辑即可,同时保持返回值格式和需求示例一致(单值不套列表):
def extend_unique(d1: dict, d2: dict) -> dict: def to_list(val): return val.copy() if isinstance(val, list) else [val] # 有序去重,保留元素原有出现顺序 def deduplicate(lst): seen = set() res = [] for item in lst: if item not in seen: seen.add(item) res.append(item) # 单值直接返回元素,多值返回列表 return res[0] if len(res) == 1 else res res = {} all_keys = d1.keys() | d2.keys() for k in all_keys: if k not in d1: res[k] = d2[k] elif k not in d2: res[k] = d1[k] else: combined = to_list(d1[k]) + to_list(d2[k]) res[k] = deduplicate(combined) return res
测试效果匹配补充需求:
d1={'a':'a','b':'b','c':'c'} d2={'b':'b','c':['d','f','g'],'e':'e'} print(extend_unique(d1, d2)) # 输出:{'a': 'a', 'b': 'b', 'c': ['c', 'd', 'f', 'g'], 'e': 'e'}
注意事项
- 代码中对列表做
copy操作是为了避免修改原字典中的列表对象,如果你不需要保留原字典的列表值不变,可以去掉.copy()提升性能 - 字典键求并集的
|运算符是Python 3.9新增特性,如果你使用低于3.9的版本,可替换为all_keys = set(d1.keys()).union(d2.keys())
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

