Python列表中嵌套字典对比问题:仅展示值变化的键与差异
对比嵌套字典列表,仅展示值变化的键与差异
嘿,我来帮你搞定这个嵌套结构对比的问题!要精准找出值发生变化的键及其差异,咱们可以写一个递归函数来逐层遍历你的嵌套列表和字典,不管层级有多深都能轻松处理。先看完整的实现方案:
示例代码
首先补全你给出的测试数据(把new的内容补全以便演示变化):
old = [ {"poker": {"John": {"Wins": 4, "Losses": 3}, "Jack": {"Wins": 6, "Losses": 1}}}, {"Blackjack": {"Bill": {"Wins": 4, "Losses": 3}, "John": {"Wins": 7, "Losses": 0}}} ] new = [ {"poker": {"John": {"Wins": 6, "Losses": 3}, "Jack": {"Wins": 6, "Losses": 2}}}, {"Blackjack": {"Bill": {"Wins": 4, "Losses": 3}, "John": {"Wins": 7, "Losses": 1}}} ] def compare_nested(old_obj, new_obj, path=""): changes = {} # 处理列表类型:按索引遍历对应元素 if isinstance(old_obj, list) and isinstance(new_obj, list): for idx, (old_item, new_item) in enumerate(zip(old_obj, new_obj)): current_path = f"{path}[{idx}]" if path else f"[{idx}]" item_changes = compare_nested(old_item, new_item, current_path) if item_changes: changes.update(item_changes) # 处理字典类型:遍历所有存在的键 elif isinstance(old_obj, dict) and isinstance(new_obj, dict): all_keys = set(old_obj.keys()).union(set(new_obj.keys())) for key in all_keys: current_path = f"{path}.{key}" if path else key if key not in old_obj: changes[current_path] = {"added": new_obj[key]} elif key not in new_obj: changes[current_path] = {"removed": old_obj[key]} else: old_val = old_obj[key] new_val = new_obj[key] # 如果是嵌套结构,递归深入对比 if isinstance(old_val, (dict, list)) and isinstance(new_val, (dict, list)): nested_changes = compare_nested(old_val, new_val, current_path) if nested_changes: changes.update(nested_changes) # 基础类型直接对比值 elif old_val != new_val: changes[current_path] = {"old": old_val, "new": new_val} return changes # 运行对比并打印结果 changes = compare_nested(old, new) for key, diff in changes.items(): print(f"{key}: {diff}")
运行结果
执行代码后,会精准输出所有值有变化的键及其差异:
[0].poker.John.Wins: {'old': 4, 'new': 6} [0].poker.Jack.Losses: {'old': 1, 'new': 2} [1].Blackjack.John.Losses: {'old': 0, 'new': 1}
关键逻辑说明
- 递归处理嵌套:函数自动识别列表、字典类型,逐层深入对比,不管你的数据有多少层嵌套都能覆盖。
- 路径追踪:通过
path参数记录当前键的层级路径(比如[0].poker.John.Wins),让你清晰知道变化发生的具体位置。 - 全场景覆盖:不仅能对比值变化,还能处理键新增/删除的情况(如果你的数据存在这类场景)。
- 灵活扩展:如果需要忽略某些特定键,或者自定义基础类型的对比规则(比如浮点数精度),直接在函数里修改对应逻辑即可。
内容的提问来源于stack exchange,提问作者DorklyDad
相关产品推荐
相关产品推荐

