Pythonで2つの辞書(dict
)を結合するには、いくつかの方法があります。Python 3.9以降では、特にシンプルな方法が導入されています。以下にいくつかの方法を紹介します。
方法1: |
演算子 (Python 3.9以降)
Python 3.9以降では、辞書を結合するためにパイプ演算子 |
を使うことができます。これは新しい辞書を返し、元の辞書を変更しません。
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
result = dict1 | dict2
print(result)
この場合、出力は以下のようになります。
{'a': 1, 'b': 3, 'c': 4}
辞書に共通のキーがある場合、dict2
の値が優先されます。
方法2: update()
メソッド
update()
メソッドを使って、1つの辞書に他の辞書の要素を追加できます。ただし、これは元の辞書を変更します。
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)
この場合、dict1
が更新されて、以下のような結果になります。
{'a': 1, 'b': 3, 'c': 4}
方法3: 辞書のアンパック (**
)
Python 3.5以降では、辞書のアンパック(**
)を使って2つの辞書を結合することができます。この方法では、新しい辞書が作成され、元の辞書は変更されません。
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
result = {**dict1, **dict2}
print(result)
結果は次のようになります。
{'a': 1, 'b': 3, 'c': 4}
方法4: ChainMapを使う方法
collections.ChainMap
を使うことで、辞書を結合することもできます。これによって、新しいマップが作成されますが、元の辞書は変更されません。
from collections import ChainMap
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
combined = ChainMap(dict2, dict1)
print(dict(combined))
この場合の出力は次の通りです。
{'a': 1, 'b': 3, 'c': 4}
各方法のポイントは、元の辞書が変更されるかどうかや、共通のキーが存在した場合の動作です。用途に応じて最適な方法を選ぶと良いでしょう。
英訳
To merge two dictionaries (dict
) in Python, there are several methods available. A particularly simple one was introduced in Python 3.9 and later. Below are some common approaches.
Method 1: |
Operator (Python 3.9+)
In Python 3.9 and later, you can use the pipe operator |
to merge dictionaries. This creates a new dictionary without modifying the original ones.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
result = dict1 | dict2
print(result)
The output will be:
{'a': 1, 'b': 3, 'c': 4}
If there are common keys, the values from dict2
will take precedence.
Method 2: update()
Method
You can use the update()
method to add the elements of one dictionary to another. Note that this modifies the original dictionary.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)
Here, dict1
is updated, and the result is:
{'a': 1, 'b': 3, 'c': 4}
Method 3: Dictionary Unpacking (**
)
From Python 3.5 onwards, you can use dictionary unpacking (**
) to merge two dictionaries. This creates a new dictionary without modifying the originals.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
result = {**dict1, **dict2}
print(result)
The result will be:
{'a': 1, 'b': 3, 'c': 4}
Method 4: Using ChainMap
You can also use collections.ChainMap
to combine dictionaries. This creates a new map, leaving the original dictionaries unchanged.
from collections import ChainMap
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
combined = ChainMap(dict2, dict1)
print(dict(combined))
The output will be:
{'a': 1, 'b': 3, 'c': 4}
Each method has different characteristics regarding whether the original dictionaries are modified and how common keys are handled. You can choose the best method based on your needs.
重要単語と熟語
- precedence: 優先、上位のこと