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 を使います。この比較では行の順序を考慮しません。