どうも、ちょげ(@chogetarou)です。
Dictionary(辞書)の特定のキー(key)を削除する方法を紹介します。
方法

Dictionary(辞書)の特定のキー(Key)を削除する方法は、2つあります。
pop()
1つは、pop()を使う方法です。
まず、辞書(Dictionary)からpop()を呼び出します。
そして、pop()の第1引数に削除するキー、第2引数にデフォルト値を指定します。
#第1引数にキー、第2引数にデフォルト値
dict.pop(key, defaultValue)
上記のpop()は、第1引数に指定したキーを呼び出した辞書(Dictionary)から削除します。
また、第1引数のキーが辞書(Dictionary)内に存在すればキーの値、存在しなければ第2引数の値を返します。
使用例
numbers = { "one":1, "two":2, "three":3 , "four":4, "five":5 }
numbers.pop("one", None)
numbers.pop("four", None)
numbers.pop("six", None)
print(numbers) #{'two': 2, 'three': 3, 'five': 5}
delステートメント
もう1つは、delステートメントを使う方法です。
具体的には、「del 辞書[キー]」のように、delの後に辞書名と[キー]を記述します。
del dict[key]
上記のdelステートメントは、[]内に指定したキーを辞書から削除します。
delステートメントは、辞書(Dictionary)に[]内のキーが存在しない場合に、エラーを起こします。
なので、 delステートメントを使う前に、キーが存在するか確認する必要があります。
#キーが存在したら、delステートメントを実行
if key in dict:
del dict[key]
使用例
numbers = { "one":1, "two":2, "three":3 , "four":4, "five":5 }
if "one" in numbers:
del numbers["one"]
if "four" in numbers:
del numbers["four"]
if "six" in numbers:
del numbers["six"]
print(numbers) #{'two': 2, 'three': 3, 'five': 5}
まとめ
Dictionary(辞書)の特定のキーを削除する方法は、次の2つです。
- pop()を使う方法
- delステートメントを使う方法
コメント