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?

Python 辞書データの.get() メソッド!

Last updated at Posted at 2025-10-03

〇〇.get(〇〇, 〇〇)
まず、使い方を思い出してみましょう。

〇〇に入るのは何でしょうか

➀リストや配列など(正確にはdict,つまり{}で作るデータ構造)
➁キー
➂キーが無い時の値

答えは➀➁➂の順で入ります。

d = {"apple": 100, "banana": 200}

print(d.get("apple", 0))   # 100
print(d.get("banana", 0))  # 200
print(d.get("grape", 0))   # 0 ← 無いキーでもエラーにならない

キーが無い時の値は、指定しなければ Noneになります。

.get() は「キーがあるか分からない辞書アクセス」に超よく使います。

0
0
1

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?