Python辞書setdefault
popitem

setdefault辞書

clear

キーがなければ default を挿入し、その値を返します。

構文

dict.setdefault(key, default?)

使用例

下記の値を入力するとサンプルに即時反映されます。

person
setdefault
print
Alice
person = {"name": "Alice"}
person.setdefault("age", 0)
print(person)  # {'name': 'Alice', 'age': 0}

person.setdefault("name", "Bob")  # 이미 있으므로 무시
print(person["name"])  # Alice