LoginSignup
0
0

More than 1 year has passed since last update.

[python] dicのgetメソッドで値取得のエラーを防ぐ

Posted at

環境

Python 3.9.13

Code

a = {"aa": True}

a["aa"]
# True

a["cc"]
# Error

a.get('cc')
# None

a.get('cc', "no exist")
# no exist

print(a)
# {'aa': True}
# 元のdicは変更されない

実用例

image.png

検索した直後のurl
https://qiita.com/search?q=aa

image.png

関連順をもう一回クリックしたら次のようになった。
https://qiita.com/search?q=aa&sort=rel

Qiitaの検索ページを見たとき、デフォルト設定が関連順になっている。
しかしurlにはsort=relがない。
sort= の値がない時にデフォルトでsort=relと読み取る

Djangoでurlからパラメータを読み取ってsortする場合を想定

getメソッドを使わない方法

try:
    sort = request.GET["sort"]
except Exception as e:
    sort = 'rel'

getメソッドを使った方法

sort = request.GET.get('sort', 'rel')

このように1行で変数を作ることができるので、エラー対策として必須で使用している

関連

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