Pythonで辞書を削除したい?Python辞書は、Pythonで使用されるデータ構造であり、キーと値のペアの形式で要素を受け入れることができます。
この記事では、Python辞書からkey-valueペアを削除するさまざまな方法を理解することになります。
Pythonで辞書を削除するためのdict.clear()
Python には、辞書を削除するための clear() メソッド が組み込まれています。
clear() メソッドは dict に存在するすべての key-value ペアを削除し、空の dict を返します。
構文は以下の通りです。
dict.clear()
|
例えば、以下の様になります。
inp_dict = {"A":"Python","B":"Java","C":"Fortan","D":"Javascript"}
print("Elements of the dict before performing the deletion operation:)
print(str(inp_dict))
inp_dict.clear()print(")
print(str(inp_dict))
|
結果は、以下の通りになります。
Elements of the dict before performing the deletion operation:
{'B': 'Java', 'D': 'Javascript', 'C': 'Fortan', 'A': 'Python'}
Elements of the dict after performing the deletion operation:
{} |
Python辞書からキーと値のペアを削除するテクニック
辞書からKey-Valueペアを削除するには、以下のテクニックを使用することができます。
- Python pop() 関数
- Pythonのdelキーワード
Python pop()関数 * Python del キーワード * Python popitem() メソッド - Python items() メソッドと一緒に辞書を理解します。
この記事もチェック:Pythonでの変数の定義やスコープ、削除、globalキーワードを解説していく
1. pop() メソッドの使用
Python の pop() メソッドは、辞書からキーとそれに関連する値、つまりキーと値のペアを削除するために使用されます。
構文は以下の通りです。
dict.pop(key)
|
pop()` メソッドは、基本的に辞書から削除するキーを受け取ります。
これは、キーとキーに関連付けられた値を辞書から削除し、更新された辞書を返します。
例えば、以下の様になります。
inp_dict = {"A":"Python","B":"Java","C":"Fortan","D":"Javascript"}
print("Elements of the dict before performing the deletion operation:)
print(str(inp_dict))
pop_item = inp_dict.pop("A")
print(")
print(str(pop_item))
print(")
print(str(inp_dict))
|
上記のコードでは、pop() メソッドの引数としてキー “A” を渡しています。
したがって、”A” に関連づけられたキーと値のペアを削除します。
結果は以下の通りです。
Elements of the dict before performing the deletion operation:
{'A': 'Python', 'B': 'Java', 'C': 'Fortan', 'D': 'Javascript'}
The deleted element:PythonElements of the dict after performing the deletion operation:
{'B': 'Java', 'C': 'Fortan', 'D': 'Javascript'}
|
この記事もチェック:Pythonの辞書(dict)をupdateメソッドで更新する方法
2. Python del キーワード
Python の del は、基本的にオブジェクトを削除するために使用されるキーワードです。
Pythonはすべてをオブジェクトとみなすので、Pythonの辞書を削除するためにdelを使えば、要素を個別に削除することが簡単にできます。
Pythonのdelキーワードは、入力辞書の値からキーと値のペアを削除するために使用することもできます。
構文は以下の通りです。
del dict[key]
|
例として以下の様になります。
inp_dict = {"A":"Python","B":"Java","C":"Fortan","D":"Javascript"}
print("Elements of the dict before performing the deletion operation:)
print(str(inp_dict))
del inp_dict["D"]
print(")
print(str(inp_dict))
|
結果は、以下の通りになります。
Elements of the dict before performing the deletion operation:
{'A': 'Python', 'B': 'Java', 'C': 'Fortan', 'D': 'Javascript'}
Elements of the dict after performing the deletion operation:
{'A': 'Python', 'B': 'Java', 'C': 'Fortan'}
|
例2: ネストされた辞書からキーと値のペアを削除する
構文は以下の様な感じです。
ネストされたPython辞書からキーと値のペアを削除することは可能です。
del キーワードは、以下のような構文でその目的を果たします。
del dict[outer-dict-key-name][key-name-associated-with-the-value]
|
例えば、以下の様になります。
inp_dict = {"Python":{"A":"Set","B":"Dict","C":"Tuple","D":"List"},
"1":"Java","2":"Fortan"}
print("Elements of the dict before performing the deletion operation:)
print(str(inp_dict))
del inp_dict["Python"]["C"]
print(")
print(str(inp_dict))
|
したがって、ここでは、外側のキー “Python” に関連付けられたキーと値のペア “C:Tuple” を削除しています。
結果は以下の通りです。
Elements of the dict before performing the deletion operation:
{'Python': {'A': 'Set', 'B': 'Dict', 'C': 'Tuple', 'D': 'List'}, '1': 'Java', '2': 'Fortan'}
Elements of the dict after performing the deletion operation:
{'Python': {'A': 'Set', 'B': 'Dict', 'D': 'List'}, '1': 'Java', '2': 'Fortan'}
|
3. Python の popitem() メソッド
Python の popitem() 関数は、Python の dict からランダムまたは任意の key-value ペアを削除するために使用されます。
popitem() 関数は引数を取らず、辞書から削除された key-value のペアを返します。
構文は以下の通りです。
dict.popitem()
|
例えば、以下の様になります。
inp_dict = {"A":"Python","B":"Java","C":"Fortan","D":"Javascript"}
print("Elements of the dict before performing the deletion operation:)
print(str(inp_dict))
pop_item = inp_dict.popitem()
print(")
print(str(pop_item))
print(")
print(str(inp_dict))
|
結果は、以下の通りになります。
Elements of the dict before performing the deletion operation:
{'A': 'Python', 'B': 'Java', 'C': 'Fortan', 'D': 'Javascript'}
The deleted element:('D', 'Javascript')
Elements of the dict after performing the deletion operation:
{'A': 'Python', 'B': 'Java', 'C': 'Fortan'}
|
この記事もチェック:Pythonのmapメソッドの使い方|ラムダ関数や引数が複数の場合の使い方も解説
4. Python Dict Comprehension と items() メソッド
Python の items() メソッドは Dict Comprehension と一緒に Python で辞書を削除するために使うことができます。
Pythonの items()メソッド は基本的に引数を取らず、特定の辞書に含まれるすべてのキーと値のペアのリストを含むオブジェクトを返します。
構文は以下の通りです。
dict.items()
|
Python の Dict Comprehension は、特定の iterable から key-value ペアを受け取って辞書を作成するために使用することができます。
構文は以下の様な感じです。
{key: value for key, value in iterable}
|
辞書から Key-value ペアを削除する場合、items() メソッドを使用して、iterable として dict comprehension に Key-value ペアのリストを提供することができます。
if ステートメント`は、先に述べた key-value に遭遇するために使用されます。
もし、言及されたキー値に遭遇したら、削除されるキーに関連するキー-値ペアを除いたすべてのキー-値ペアを含む新しい dict を返します。
例えば、以下の様になります。
inp_dict = {"A":"Set","B":"Dict","C":"Tuple","D":"List",
"1":"Java","2":"Fortan"}
print("Elements of the dict before performing the deletion operation:)
print(str(inp_dict))
res_dict = {key:value for key, value in inp_dict.items() if key != "1"}
print(")
print(str(res_dict))
|
結果は、以下の通りになります。
Elements of the dict before performing the deletion operation:
{'A': 'Set', 'B': 'Dict', 'C': 'Tuple', 'D': 'List', '1': 'Java', '2': 'Fortan'}
Elements of the dict after performing the deletion operation:
{'A': 'Set', 'B': 'Dict', 'C': 'Tuple', 'D': 'List', '2': 'Fortan'}
|
Pythonで辞書を削除する(反復処理中に要素を指定する) ## Delete a Dictionary in Python
Pythonの辞書を扱っていると、辞書の反復処理中にキーと値のペアを削除したい場面に出くわすことがあります。
このような場合、入力辞書のリストを作成し、forループを使用して辞書のリストを走査することができます。
構文は以下の様な感じです。
list(dict)
|
最後に、if文を使って、削除するキーに遭遇するかどうかをループでチェックします。
キーに遭遇したらすぐに、del キーワードを使ってキーと値のペアを削除することができます。
例えば、以下の様になります。
inp_dict = {"A":"Set","B":"Dict","C":"Tuple","D":"List",
"1":"Java","2":"Fortan"}
print("Elements of the dict before performing the deletion operation:)
print(str(inp_dict))
for KEY in list(inp_dict):
if KEY =="B":
del inp_dict[KEY]
print(")
print(str(inp_dict))
|
結果は以下の通りです。
Elements of the dict before performing the deletion operation:
{'A': 'Set', 'B': 'Dict', 'C': 'Tuple', 'D': 'List', '1': 'Java', '2': 'Fortan'}
Elements of the dict after performing the deletion operation:
{'A': 'Set', 'C': 'Tuple', 'D': 'List', '1': 'Java', '2': 'Fortan'}
|
まとめ
以上、Python辞書からKey-Valueペアを削除するさまざまなテクニックを公開しました。