Python 参考

运行 Python 示例,学习比较字典、生成键顺序固定的 JSON,以及按次数比较重复行。

运行示例

将每个示例单独保存为 example.py,运行 python3 example.py。示例均使用 Python 标准库。

比较字典的键和值

对键视图做差集,找出新增或删除的键。只比较两份字典共有的键值,再分别排序,让结果顺序固定。

python
before = {"port": 80, "host": "localhost"}
after = {"port": 8080, "debug": False}

print("added:", sorted(after.keys() - before.keys()))
print("removed:", sorted(before.keys() - after.keys()))
changed = [key for key in before.keys() & after.keys() if before[key] != after[key]]
print("changed:", sorted(changed))

预期输出

added: ['debug']
removed: ['host']
changed: ['port']

常见误区

两侧都用 get() 可能把缺少的键和显式设为 None 的键混为一谈。先检查键是否存在。

官方文档

先统一 JSON 格式,再做文本对比

先解析 JSON,再按键排序并使用固定的分隔符输出。这样可以去掉格式差异,同时保留数组顺序。

python
import json

data = json.loads('{"port": 80, "host": "localhost"}')
print(json.dumps(data, sort_keys=True, separators=(",", ":"), ensure_ascii=False))

预期输出

{"host":"localhost","port":80}

常见误区

默认解码器会保留重复键的最后一个值。如果重复键本身有意义,请在格式化前单独检查。

官方文档

用 Counter 比较每行出现的次数

Counter 相减只保留正的差值。分别正向和反向相减,即可找出两侧各自多出的行。

python
from collections import Counter

before = Counter(["apple", "apple", "pear"])
after = Counter(["apple", "pear", "pear"])
print("removed:", dict(before - after))
print("added:", dict(after - before))

预期输出

removed: {'apple': 1}
added: {'pear': 1}

常见误区

集合会去掉重复项。只判断是否出现时用集合,需要比较次数时用 Counter。这个方法忽略行的先后顺序。

官方文档

相关工具