Python辞書setdefault()メソッド
例
「モデル」アイテムの値を取得します。
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)
定義と使用法
このsetdefault()
メソッドは、指定されたキーを持つアイテムの値を返します。
キーが存在しない場合は、指定された値でキーを挿入します。以下の例を参照してください。
構文
dictionary.setdefault(keyname, value)
パラメータ値
Parameter | Description |
---|---|
keyname | Required. The keyname of the item you want to return the value from |
value | Optional. If the key exist, this parameter has no effect. If the key does not exist, this value becomes the key's value Default value None |
その他の例
例
「color」アイテムの値を取得します。「color」アイテムが存在しない場合は、値「white」で「color」を挿入します。
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("color",
"white")
print(x)