1. はじめに
Pythonの辞書型(dict)は、データを「キーと値のペア」で管理するための便利なデータ型です。たとえば「名前と年齢」「商品と価格」など、関連するデータを一括で扱えるため、実務でも頻繁に使われます。
本記事では、「Python|辞書型(dict)の操作方法と実用例」をテーマに、基本的な使い方から実務でも役立つ応用テクニックまでを初心者にもわかりやすく解説します。
2. Pythonの辞書型(dict)の基本構文
2.1 辞書の作成と基本構造
Pythonの辞書は、{キー: 値}
の形式で定義します。
# 辞書の例
user = {
"name": "Taro",
"age": 25,
"email": "taro@example.com"
}
print(user)
実行結果:
{'name': 'Taro', 'age': 25, 'email': 'taro@example.com'}
2.2 辞書の値を取得・変更する
# 値の取得
print(user["name"]) # "Taro"
# 値の更新
user["age"] = 26
print(user["age"]) # 26
実行結果:
Taro
26
2.3 要素の追加・削除
# 新しいキーを追加
user["gender"] = "male"
# キーを削除
del user["email"]
print(user)
実行結果:
{'name': 'Taro', 'age': 26, 'gender': 'male'}
3. よくある使い方・応用例
3.1 for文で辞書をループ処理
.items()
を使うことで、キーと値を同時に取得できます。
for key, value in user.items():
print(f"{key} → {value}")
実行結果:
name → Taro
age → 26
gender → male
3.2 キーが存在するか確認する
if "email" in user:
print("メールアドレスがあります。")
else:
print("メールアドレスは未登録です。")
実行結果:
メールアドレスは未登録です。
3.3 辞書の結合(マージ)
other_info = {"email": "new@example.com", "age": 30}
user.update(other_info)
print(user)
実行結果:
{'name': 'Taro', 'age': 30, 'gender': 'male', 'email': 'new@example.com'}
3.4 実務で役立つ:JSONデータとの変換
import json
# 辞書 → JSON文字列
json_str = json.dumps(user)
print(json_str)
# JSON文字列 → 辞書
user_dict = json.loads(json_str)
print(user_dict)
実行結果:
{"name": "Taro", "age": 30, "gender": "male", "email": "new@example.com"}
{'name': 'Taro', 'age': 30, 'gender': 'male', 'email': 'new@example.com'}
4. 辞書操作の注意点とエラー対策
4.1 存在しないキーの参照はエラーに
# print(user["address"]) # KeyError!
# 安全に取得する方法
print(user.get("address", "未登録"))
実行結果:
未登録
4.2 キーに使えるのは「変更不可型」のみ
辞書のキーにはstr
、int
、tuple
などのイミュータブル型のみが使えます。リストなどは使えません。
4.3 辞書のコピーは浅いコピーに注意
# 辞書のコピーは元のオブジェクトに影響することがある
original = {"scores": [80, 90]}
copy_dict = original.copy()
copy_dict["scores"].append(70)
print(original)
実行結果:
{'scores': [80, 90, 70]}
5. まとめ
- 辞書型(dict)は、「キーと値」を効率よく扱えるPythonの代表的なデータ構造
- 基本操作(取得・更新・追加・削除)はシンプルで覚えやすい
- for文との併用、JSON変換など応用範囲が広い
- 存在しないキーの参照や、コピーの扱いに注意
辞書はPythonプログラミングにおいて、データ構造の中心的存在です。データの検索・格納が高速で、Web開発・機械学習・業務自動化など、あらゆる場面で活躍します。使いこなせるようになることで、Pythonのスキルが一段階アップすること間違いなしです!