I want to return the default value when a value that is not in the dictionary is entered.
I don't know the exact name of the default value, but if you put =
after the argument, it will use that value when the function argument is not given.
Function default arguments
def func(arg1):
print(arg1)
# $ func() #Causes an error with no arguments
# [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): #If there is a default argument, it will automatically use the default argument even if there is no argument
print(arg1)
# $ func()
# [Out] # 0
Like this default argument in the dictionary
In such a case, use the get method.
get method docstring
dict.get? Docstring: D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
dict.get method
dic={'a':6,'b':4}
# $ dic['a']
# 6
# $ dic['b']
# 4
# $ dic['c'] #Error if a value that is not in the key is entered
# ---------------------------------------------------------------------------
# KeyError Traceback (most recent call last)
# <ipython-input-11-0c3be353eb91> in <module>()
# ----> 1 ic['c']
# KeyError: 'c'
$ dic.get('c',0) #In dic'c'The second argument is returned because there is no
# [Out] # 0
Also, if the second argument is not specified for get
, None
is returned.
Reference: Return None if Dictionary key is not available
Recommended Posts