0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

辞書(dict)を使いこなす【Day 14】

0
Last updated at Posted at 2025-12-13

Qiita Advent Calendar 2025 のパイソニスタの一人アドカレ Day14 の記事です。

辞書(dict)を使いこなす

辞書(dict)は、**「キー」と「値」のセットをまとめて扱う」**ためのデータ型です。
「名前 → 電話番号」「商品名 → 価格」など、意味のあるペアを保存するのに最適です。

辞書の基本形

user = {
    "name": "Alice",
    "age": 25,
    "country": "Japan"
}

キー(左)値(右) の形で記述します。

値の取り出し

print(user["name"])  # Alice
print(user["age"])   # 25

値の変更

user["age"] = 26

新しいキーと値を追加

user["email"] = "alice@example.com"

キーと値を削除

del user["country"]

辞書の便利なメソッド

keys:キー一覧

print(user.keys())

values:値一覧

print(user.values())

items:キーと値のペア一覧

for key, value in user.items():
    print(key, value)

辞書のよくある使いどころ

1. ユーザー情報の管理

user = {"name": "Alice", "age": 25}

2. 条件分岐の代わりとしてマッピング

prices = {"apple": 100, "banana": 80}

fruit = "apple"
print(prices[fruit])  # 100

条件分岐を使わずに値を引けるのが便利です。

よくあるミス

存在しないキーを呼び出してエラー

print(user["address"])  # KeyError

対処:get() を使う

print(user.get("address"))          # None
print(user.get("address", "なし"))  # なし

まとめ

  • dict は「キー → 値」を扱うデータ型
  • user["name"] のようにキーで値を取り出す
  • 追加・変更・削除が簡単
  • keys() / values() / items() はよく使う
  • 存在しないキーを呼ぶとエラー、get() が便利
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?