LoginSignup
0
0

More than 5 years have passed since last update.

ディクショナリにデフォルト値ってないのか?

Posted at

ディクショナリにない値が入力されたとき、デフォルト値を返したい。

デフォルト値とは正確な名前かわからないが、引数の後に=入れておけばfunctionの引数が与えられなかったときにその値使ってくれるというやつ。

関数のデフォルト引数
def func(arg1):
    print(arg1)

 # $ func()   # 引数がないとエラー起こす
 # [Out]
 # ---------------------------------------------------------------------------
 # TypeError                                 Traceback (most recent call last)
 # <ipython-input-6-08a2da4138f6> in <module>()
 # ----> 1 func()

 # TypeError: func() missing 1 required positional argument: 'arg1'


def func(arg1=0):   # デフォルト引数があれば引数なくても自動でデフォルト引数を使ってくれる
    print(arg1)

 # $ func()
 # [Out] # 0

このデフォルト引数みたいに辞書にも
1. キーのない値が入力されたとき
2. 指定した値を返す
っていうのがほしい。

こういうときはgetメソッドを使う。

get method docstring

dict.get?
Docstring: D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.

dict.getメソッド
dic={'a':6,'b':4}
 # $ dic['a']
 # 6

 # $ dic['b']
 # 4

 # $ dic['c']   # キーにない値が入力されるとエラー
 # ---------------------------------------------------------------------------
 # KeyError                                  Traceback (most recent call last)
 # <ipython-input-11-0c3be353eb91> in <module>()
 # ----> 1 ic['c']

 # KeyError: 'c'

$ dic.get('c',0)   # dic内に'c'がないので第二引数が返される
 # [Out] # 0

また、getに第二引数を指定しなければ、Noneが返される。

参考:Return None if Dictionary key is not available

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