4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Python]dictのKeyErrorを排除する

Posted at

dictのkeyを指定して値を読み出すとき、存在しないkey値を指定するとKeyErrorが発生するため、以下のようにエラー処理を入れていました。

python
>>> num_dict = {1: "one", 2: "two", 3: "three"}

>>> def get_english_number(num):
...    try:
...        english_number = num_dict[num]
...    except KeyError:
...        english_number = "辞書にない数字です"
...    return english_number

>>> get_english_number(1)
'one'

>>> get_english_number(4)
'辞書にない数字です'

dictのget()関数を使うことでエラー処理を排除することができます。

エラー処理を排除
>>> num_dict = {1: "one", 2: "two", 3: "three"}

>>> def get_english_number(num):
...    english_number = num_dict.get(num, "辞書にない数字です")
...    return english_number

>>> get_english_number(1)
'one'

>>> get_english_number(4)
'辞書にない数字です'

存在しないkeyを指定した場合get()関数の第二引数の値が返されます。

エラー処理を入れるよりコードが少しすっきりしたと思います。

4
3
2

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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?