概要
Pythonで「辞書から要素を削除する」の動作を確認してみました。
以下のページを参考にしました。
実装
以下のファイルを作成しました。
sample.py
mydict = {"A":"Apple", "L":"Lemon", "O":"Orange"}
del mydict["L"]
print(mydict)
mydict = {"A":"Apple", "L":"Lemon", "O":"Orange"}
#del mydict["P"]
mydict = {"A":"Apple", "L":"Lemon", "O":"Orange"}
val = mydict.pop("L")
print(val)
print(mydict)
mydict = {"A":"Apple", "L":"Lemon", "O":"Orange"}
#val = mydict.pop("P")
mydict = {"A":"Apple", "L":"Lemon", "O":"Orange"}
val = mydict.pop("P", "Not Found")
print(val)
print(mydict)
mydict = {"A":"Apple", "L":"Lemon", "O":"Orange"}
val = mydict.popitem()
print(val)
print(mydict)
val = mydict.popitem()
print(val)
print(mydict)
val = mydict.popitem()
print(val)
print(mydict)
mydict = {"A":"Apple", "L":"Lemon", "O":"Orange"}
mydict.clear()
print(mydict)
以下のコマンドを実行しました。
$ python3 sample.py
{'A': 'Apple', 'O': 'Orange'}
Lemon
{'A': 'Apple', 'O': 'Orange'}
Not Found
{'A': 'Apple', 'L': 'Lemon', 'O': 'Orange'}
('O', 'Orange')
{'A': 'Apple', 'L': 'Lemon'}
('L', 'Lemon')
{'A': 'Apple'}
('A', 'Apple')
{}
{}
まとめ
何かの役に立てばと。