Python-辞書アイテムを削除する
アイテムの削除
辞書からアイテムを削除するには、いくつかの方法があります。
例
このpop()
メソッドは、指定されたキー名を持つアイテムを削除します。
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
例
このpopitem()
メソッドは、最後に挿入されたアイテムを削除します(3.7より前のバージョンでは、代わりにランダムなアイテムが削除されます)。
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
例
del
キーワードは、指定されたキー名を持つアイテムを削除します。
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
例
del
キーワードは辞書を完全に削除することもできます:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict"
no longer exists.
例
このclear()
メソッドは辞書を空にします。
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)