この記事では、Pythonで辞書をマージするすべてのメソッドについて説明します。
辞書は、Pythonでデータを格納する便利な方法です。
彼らは、キーと値のペアの形でデータを格納します。
辞書を使用している間、あなたは2つの辞書をマージしたいと思うかもしれません。
Pythonで辞書をマージするさまざまな方法
2つの辞書をマージする場合、その方法は1つだけではありません。
この記事では、2つの辞書をマージするために使用できるさまざまな方法について説明します。
1. forループの使用
ある辞書の項目を別の辞書にコピーするために、forループを使うことができる。
これは、2つの辞書をマージする素朴な方法です。
片方の辞書をforループで反復処理し、同時にもう片方の辞書にエントリーを追加する必要があります。
これを行うためのPythonコードは以下の通りです。
dict1 = { 'Rahul': 4, 'Ram': 9, 'Jayant' : 10 }
dict2 = { 'Jonas': 4, 'Niel': 9, 'Patel' : 10 }
print("Before merging")
print("dictionary 1:", dict1)
print("dictionary 2:", dict2)
dict3 = dict1.copy()
for key, value in dict2.items():
dict3[key] = value
print("after updating :")
print(dict3)
|
dict1.update(dict2) |
2. .update()の使用
Pythonの辞書には、2つの辞書をマージするためのメソッドが組み込まれています。
片方の辞書でこのメソッドを呼び出し、もう片方の辞書を引数として渡すことができます。
これは次のようなコードで実現できます。
dict1 = { 'Rahul': 4, 'Ram': 9, 'Jayant' : 10 }
dict2 = { 'Jonas': 4, 'Niel': 9, 'Patel' : 10 }
print("Before merging")
print("dictionary 1:", dict1)
print("dictionary 2:", dict2)
dict1.update(dict2)print("after updating :")
print(dict1)
|
完全なコードは次のようになる。
dict3 = {**dict1, **dict2}
|
dict3 = {**dict1, **dict2, **dict3}
|
updateメソッドの欠点は、引数として1つの辞書しか渡せないことです。
このため、一度にマージできるのは2つの辞書に限られます。
複数の辞書をマージするには、 ** (kwargs) オペレータを使用します。
これは次に見ていきます。
この記事もチェック:Pythonの辞書(dict)をupdateメソッドで更新する方法
3. 3.Using ****kwargs
Kwargsは別名unpack演算子(unpacking operator)で、2つ以上の辞書を結合することができます。
KwargsはKeyword Argumentsの略です。
KwargsはKeyword Argumentsの略で、可変長のKey-Valueペアを送信することができます。
このように、”unpacking operator “を使って辞書をマージするには、以下のように記述します。
dict1 = { 'Rahul': 4, 'Ram': 9, 'Jayant' : 10 }
dict2 = { 'Jonas': 4, 'Niel': 9, 'Patel' : 10 }
dict3 = { 'John': 8, 'Naveen': 11, 'Ravi' : 15 }
print("Before merging")
print("dictionary 1:", dict1)
print("dictionary 2:", dict2)
print("dictionary 3:", dict3)
dict3 = {**dict1, **dict2, **dict3}
print("after updating :")
print(dict3)
|
完全なコードは次のとおりです。
dict1 |= dict2
|
同じ方法で、2つ以上の辞書をマージすることもできます。
dict1 = { 'Rahul': 4, 'Ram': 9, 'Jayant' : 10 }
dict2 = { 'Jonas': 4, 'Niel': 9, 'Patel' : 10 }
print("Before merging")
print("dictionary 1:", dict1)
print("dictionary 2:", dict2)
dict1 |= dict2
print("after updating :")
print(dict1)
|
完全なコードは次のとおりです。


4. マージ演算子の使用
辞書をマージするのに最適な方法は、マージ演算子を使用することです。
マージ演算子を使うと、マージ操作が非常に簡単になる。
次のコードで、2つの辞書をマージすることができます。

完全なコードは次のとおりです。


まとめ
この記事では、Pythonで辞書をマージするために使用できる4つの異なる方法について説明しました。
楽しく学んでいただければ幸いです。