0
1

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 3 years have passed since last update.

Python dict でキーがなかったらデフォルト値を返すメモ

Last updated at Posted at 2021-01-03

パラメータなどを dict で扱っている.

パラメータ定義(キー)がなかったらデフォルト値を返すようにしたい.

val = None # Set default
if 'filename' in config:
    val = config['filename']

や, one liner で

val = config['filename'] if 'filename' in config else None

という書き方があるが, ややこしい.

get を使う

get の第二引数でキーがなかった場合のデフォルト値を設定できました!

val = config.get('filename', None)

わかりやすいですね!

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?