辞書は「キーで引く」データ構造
リストが位置(インデックス)でアクセスするのに対して、Python の辞書(dict)はキー で値を引きます。キーには文字列や数値を使うのが一般的で、それぞれが対応する値にひも付きます。このシンプルな発想の転換だけで、在庫管理、設定ファイル、JSON データ、ユーザープロフィール、キャッシュなど、応用範囲が一気に広がります。
prices = {
"apple": 0.50,
"bread": 2.00,
"milk": 1.20,
}
print(prices["apple"])
print(prices["bread"])Master Python the hands-on way
Interactive lessons, real projects, and instant feedback.
START NOW
キーと値には、ほぼ何でも入れられます。キーはハッシュ可能である必要があり(数値、文字列、タプルはOK。リストや別の辞書はNG)、値には特に制限はありません。辞書の中に辞書やリストを入れることもできます。
Python 辞書の作り方
作り方はいくつかあって、それぞれ使いどころが違います。
# Literal with braces
user = {"name": "Rosa", "age": 30, "city": "Lisbon"}
print(user)
# Empty dict, built up over time
counts = {}
counts["a"] = 1
counts["b"] = 2
print(counts)
# From a list of (key, value) pairs
pairs = [("one", 1), ("two", 2), ("three", 3)]
mapping = dict(pairs)
print(mapping)
# With keyword arguments
config = dict(host="localhost", port=8080, debug=True)
print(config)
値を取り出す
取り出し方は2通りありますが、どちらを使うかで挙動が変わります。
prices = {"apple": 0.50, "bread": 2.00}
# [] - direct indexing. KeyError if missing.
print(prices["apple"])
# .get() - returns None (or a default) if missing.
print(prices.get("milk")) # None
print(prices.get("milk", 0.00)) # 0.00
用途で使い分けましょう。
[] を使う場面 : そのキーが 絶対に 存在しているはずのとき。もし無ければそれはバグなので、エラーで派手に落ちてくれた方が助かります。
.get() を使う場面 : 「キーが無いこともある」が正常系のとき。try/except を書かずにデフォルト値を返せます。
要素の追加・更新・削除
キーに値を代入すれば、新規作成も上書きもこれ一つで済みます。
prices = {"apple": 0.50, "bread": 2.00}
prices["milk"] = 1.20 # new key
prices["apple"] = 0.60 # existing key, overwritten
print(prices)
del prices["bread"] # remove a key; KeyError if missing
print(prices)
gone = prices.pop("apple") # remove and return; accepts a default
print("was:", gone, "now:", prices)
# pop with a default so it doesn't raise
prices.pop("missing", None)
update() は別の辞書やキーと値のペアのイテラブルをマージします:
settings = {"theme": "dark", "font": "mono"}
overrides = {"font": "sans", "zoom": 1.2}
settings.update(overrides)
print(settings)
overrides と settings で同じキーがあると、overrides 側で上書きされます。
キーの存在確認
in で調べられるのはキーであって、値ではありません。
user = {"name": "Rosa", "age": 30}
print("name" in user) # True
print("email" in user) # False
print("Rosa" in user) # False - that's a value, not a key
値だけをチェックしたいときは、user.values() を使います。
print(30 in user.values())
辞書をループで回す方法
python 辞書のループには、次の3つのビューが使えます。
scores = {"ada": 90, "rosa": 85, "malik": 78}
# Keys (the default)
for name in scores:
print(name)
# Values
for score in scores.values():
print(score)
# Both - the common case
for name, score in scores.items():
print(f"{name}: {score}")
.items() は実戦で一番出番が多い書き方です。キーと値のペアを展開した状態で受け取れるので、そのまま使い始められます。
ループの順序については、Python 3.7 以降なら挿入順が保持されます。辞書は「中身の順番が適当な入れ物」ではありません。a → b → c の順に追加したなら、ループもその順で回ります。これは言語仕様として保証されている挙動なので、安心して頼って大丈夫です。
Python 辞書のソート方法
辞書は挿入順を保つ仕様なので、「辞書をソートする」というのは実質、狙った順番でキーを入れ直した新しい辞書を作る という意味になります。
scores = {"rosa": 85, "ada": 90, "malik": 78}
# Sort by key
by_key = dict(sorted(scores.items()))
print(by_key)
# Sort by value (ascending)
by_value = dict(sorted(scores.items(), key=lambda item: item[1]))
print(by_value)
# Sort by value, descending
top = dict(sorted(scores.items(), key=lambda item: item[1], reverse=True))
print(top)
sorted() はタプルのペアからなるリストを返すので、それを dict(...) で包み直せば、新しい順序の辞書ができあがります。並び替えたペアだけ欲しくて辞書にする必要がなければ、外側の dict() は省いてOKです。
python 辞書を結合する方法
Python 3.9以降では、| 演算子が使えます。
defaults = {"theme": "dark", "font": "mono"}
overrides = {"font": "sans", "zoom": 1.2}
merged = defaults | overrides
print(merged)
キーが衝突した場合は、後ろ側の辞書の値が優先されます。インプレースで同じことをしたいときは .update() を使いましょう。古いバージョンの Python を使っている場合は {**defaults, **overrides} という書き方で対応できます。
setdefault パターン
実務でよく出てくるのが、「キーがあればその値を使い、なければデフォルト値をセットしてから使う」というパターンです。
counts = {}
for word in ["one", "two", "one", "three", "two", "one"]:
counts.setdefault(word, 0)
counts[word] += 1
print(counts)
より簡単なのは、collections.Counter を使う方法です。
from collections import Counter
words = ["one", "two", "one", "three", "two", "one"]
print(Counter(words))
Counter は dict のサブクラスで、要素の出現回数を数えるのに特化したクラスです。「何かの登場回数をカウントしたい」と思ったら、まず候補に挙がるのがこれ。
辞書内包表記
リスト内包表記と同じノリで、辞書をサッと作れる書き方です:
numbers = [1, 2, 3, 4, 5]
squares = {n: n * n for n in numbers}
print(squares)
# Invert a dict (keys become values and vice versa)
prices = {"apple": 0.50, "bread": 2.00}
lookup = {v: k for k, v in prices.items()}
print(lookup)
ルールはリスト内包表記と同じで、{} の中に key: value を書くだけです。
JSON とそっくりな辞書
Python の辞書は JSON オブジェクトとほぼそのまま対応しています。相互変換もワンライナーで済みます。
import json
data = {"name": "Rosa", "age": 30, "tags": ["python", "docs"]}
as_json = json.dumps(data)
print(as_json)
back = json.loads(as_json)
print(back)
Web 開発で辞書をよく見かけるのはこれが理由です。API のリクエストやレスポンスは、結局のところネットワークを挟んだ dict 操作そのものなんです。
実践例:ユーザープロファイル
設定ファイルっぽい感じで、ユーザー情報を管理する小さなプログラムを書いてみましょう。
user = {
"name": "Rosa",
"email": "rosa@example.com",
"preferences": {
"theme": "dark",
"notifications": True,
},
"tags": ["python", "docs"],
}
print(user["name"])
print(user["preferences"]["theme"])
print(user.get("last_login", "never"))
user["tags"].append("seo")
user["preferences"]["theme"] = "light"
print(user)
ネストされた辞書、ミュータブルな値、デフォルト値付きの .get() --レコード型のデータを扱うときの基本ツールはこれで一通りそろいました。
次のステップ
リスト、タプル、セット、辞書。この4つのコレクションさえ押さえておけば、プログラミング初期に出会うデータのほとんどはモデリングできます。次に学ぶのはリスト内包表記です。あるコレクションを別のコレクションへと変換する、Pythonらしいコンパクトな書き方を見ていきましょう。