Pythonにおけるdict型とは、他の言語ではハッシュなどと呼ばれているような、キー(Key)とバリュー(Value)を有するデータ構造です。
今回は、Pythonでdict型を扱うときに必要な基本的な関数から知っていると便利な関数まで、全部まとめます。
本記事の内容
- dict型の基本的な作成方法
- 要素の取得・追加・更新・削除
- 便利な関数・メソッド
- 辞書内包表記とソート
dict型の作成
# 基本的な作成方法
d1 = {"a": 1, "b": 2, "c": 3}
print(d1) # {'a': 1, 'b': 2, 'c': 3}
# dict()コンストラクタ
d2 = dict(x=10, y=20, z=30)
print(d2) # {'x': 10, 'y': 20, 'z': 30}
# タプルのリストから作成
d3 = dict([("name", "Alice"), ("age", 25), ("city", "Tokyo")])
print(d3) # {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
# zip を利用した作成
keys = ["a", "b", "c"]
values = [1, 2, 3]
d4 = dict(zip(keys, values))
print(d4) # {'a': 1, 'b': 2, 'c': 3}
要素の取得
基本的なアクセス
d = {"a": 1, "b": 2, "c": 3}
# キーで直接アクセス
print(d["a"]) # 1
# 存在しないキーにアクセスするとKeyError
# print(d["z"]) # KeyError: 'z'
get関数
dict型は、保持していないKeyにアクセスしようとすると、KeyErrorを出してしまいます。get関数を通して指定したKeyのValueにアクセスしようとすると、保持していないKeyに対してはデフォルト値を返してくれます。
d = {"a": 1, "b": 2}
# get関数: キーがなければデフォルト値を返す
print(d.get("a", 0)) # 1
print(d.get("c", 0)) # 0(デフォルト値)
print(d.get("c")) # None(デフォルト値未指定)
keys / values / items
d = {"a": 1, "b": 2, "c": 3}
# キーの一覧
print(list(d.keys())) # ['a', 'b', 'c']
# 値の一覧
print(list(d.values())) # [1, 2, 3]
# キーと値のペア
print(list(d.items())) # [('a', 1), ('b', 2), ('c', 3)]
# for ループでの利用
for key, value in d.items():
print(f" {key}: {value}")
要素の追加・更新・削除
d = {"a": 1, "b": 2}
# 追加(新しいキーに代入)
d["c"] = 3
print(d) # {'a': 1, 'b': 2, 'c': 3}
# 更新(既存のキーに代入)
d["a"] = 100
print(d) # {'a': 100, 'b': 2, 'c': 3}
# update関数で一括更新
d.update({"b": 200, "d": 4})
print(d) # {'a': 100, 'b': 200, 'c': 3, 'd': 4}
# 削除: del
del d["d"]
print(d) # {'a': 100, 'b': 200, 'c': 3}
# 削除: pop(削除した値を返す)
removed = d.pop("c")
print(f"removed: {removed}") # removed: 3
print(d) # {'a': 100, 'b': 200}
# popで存在しないキーを指定した場合のデフォルト値
removed = d.pop("z", None)
print(f"removed: {removed}") # removed: None
便利なメソッド
setdefault
キーが存在しなければデフォルト値を設定し、存在すれば既存の値を返します。
d = {"a": 1, "b": 2}
# キーが存在しない場合: 設定して返す
val = d.setdefault("c", 3)
print(val) # 3
print(d) # {'a': 1, 'b': 2, 'c': 3}
# キーが存在する場合: 既存の値を返す(上書きしない)
val = d.setdefault("a", 999)
print(val) # 1(元の値のまま)
defaultdict
collectionsモジュールの defaultdict を使うと、存在しないキーにアクセスした際にデフォルト値が自動で設定されます。
from collections import defaultdict
# int のデフォルト値(0)
counter = defaultdict(int)
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
for word in words:
counter[word] += 1
print(dict(counter)) # {'apple': 3, 'banana': 2, 'cherry': 1}
# list のデフォルト値(空リスト)
grouped = defaultdict(list)
pairs = [("fruit", "apple"), ("fruit", "banana"), ("veg", "carrot"), ("veg", "onion")]
for category, item in pairs:
grouped[category].append(item)
print(dict(grouped)) # {'fruit': ['apple', 'banana'], 'veg': ['carrot', 'onion']}
Counter
要素の出現回数をカウントする特殊な辞書です。
from collections import Counter
# リストの要素をカウント
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
c = Counter(words)
print(c) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
# 最頻出の要素
print(c.most_common(2)) # [('apple', 3), ('banana', 2)]
# 文字列の文字をカウント
char_count = Counter("hello world")
print(char_count) # Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ...})
辞書内包表記
リスト内包表記と同様に、辞書も内包表記で簡潔に作成できます。
# 基本的な辞書内包表記
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 条件付き
even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares) # {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
# キーと値の入れ替え
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
# 文字列リストから辞書を作成
words = ["apple", "banana", "cherry"]
length_dict = {word: len(word) for word in words}
print(length_dict) # {'apple': 5, 'banana': 6, 'cherry': 6}
辞書のソート
d = {"banana": 3, "apple": 1, "cherry": 2}
# キーでソート
sorted_by_key = dict(sorted(d.items()))
print(sorted_by_key) # {'apple': 1, 'banana': 3, 'cherry': 2}
# 値でソート
sorted_by_value = dict(sorted(d.items(), key=lambda x: x[1]))
print(sorted_by_value) # {'apple': 1, 'cherry': 2, 'banana': 3}
# 値の降順でソート
sorted_desc = dict(sorted(d.items(), key=lambda x: x[1], reverse=True))
print(sorted_desc) # {'banana': 3, 'cherry': 2, 'apple': 1}
辞書のマージ(Python 3.9以降)
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
# | 演算子によるマージ (Python 3.9+)
merged = d1 | d2
print(merged) # {'a': 1, 'b': 3, 'c': 4} # 重複キーは右辺優先
# |= 演算子による更新 (Python 3.9+)
d1_copy = d1.copy()
d1_copy |= d2
print(d1_copy) # {'a': 1, 'b': 3, 'c': 4}
# Python 3.8以前の方法
merged_old = {**d1, **d2}
print(merged_old) # {'a': 1, 'b': 3, 'c': 4}
実践例: 単語の出現頻度分析
import matplotlib.pyplot as plt
from collections import Counter
# サンプルテキスト
text = """
Python is a programming language that lets you work quickly
and integrate systems more effectively Python is easy to learn
and Python has an elegant syntax
"""
# 単語の出現頻度をカウント
words = text.lower().split()
word_counts = Counter(words)
# 上位10件を取得
top_10 = word_counts.most_common(10)
print("=== Top 10 Words ===")
for word, count in top_10:
print(f" {word}: {count}")
# 可視化
words_top, counts_top = zip(*top_10)
plt.figure(figsize=(10, 4))
plt.barh(range(len(words_top)), counts_top, color='steelblue', alpha=0.8)
plt.yticks(range(len(words_top)), words_top)
plt.xlabel("Count")
plt.title("Word Frequency (Top 10)")
plt.gca().invert_yaxis()
plt.grid(True, alpha=0.3, axis='x')
plt.tight_layout()
plt.show()
まとめ
本記事では、Pythonのdict型(辞書型)の使い方を網羅的にまとめました。
- dict型はキーとバリューのペアでデータを管理するデータ構造
- get関数で安全に値を取得でき、KeyErrorを防げる
- defaultdictやCounterなど、用途に特化した辞書クラスが標準ライブラリにある
- 辞書内包表記で簡潔に辞書を作成できる
- Python 3.9以降は
|演算子で辞書のマージが可能