LoginSignup
9
5

More than 3 years have passed since last update.

[python] 辞書の結合

Last updated at Posted at 2021-04-22

※Python3.9以降はもっと簡単な方法があるので、追記:Python3.9以降の場合を参照ください!

Case1: 片方の辞書にもう片方を追加する (上書き)

結論

以下のように、update()メソッドを使う。

d1 = {'one':1, 'two':2}
d2 = {'two':'ii', 'three':'iii'}
d1.update(d2)
print(d1)
# {'one': 1, 'two': 'ii', 'three': 'iii'}

重複するキーがある場合は、update()の中身が優先(中身で上書き)される。

なお、2つの辞書を同時に追加する場合は、以下のようにする。

d1 = {'one':1, 'two':2}
d2 = {'two':'ii', 'three':'iii'}
d3 = {'three':'III', 'four':'IV'}
d1.update(d2,**d3)
print(d1)
# {'one': 1, 'two': 'ii', 'three': 'III', 'four': 'IV'}

アスタリスク2つ(**)が何か、は後述のアスタリスク2つの正体を参照。
なお、3つ以上の辞書でupdate()することはできない模様。

Case2: 2つの辞書を結合した新しい辞書を生成する

結論

以下のようにする。

d1 = {'1':1, '2':2}
d2 = {'2':'ii', '3':'iii'}
d3 = dict(d1, **d2)
print(d3)
# {'1': 1, '2': 'ii', '3': 'iii'}

上書きの場合と同様に、重複するキーがある場合は、後ろに指定された辞書の中身が優先(中身で上書き)される。
なお、3つ以上の辞書を結合することはできない模様。

また、python3.5以降ならば、dict()の代わりに{}が使える。
{}を使って以下のようにすれば3つ以上の辞書を同時に結合できる。

d1 = {'one':1, 'two':2}
d2 = {'two':'ii', 'three':'iii'}
d3 = {'three':'III', 'four':'IV'}
d4 = {**d1, **d2, **d3}
print(d4)
# {'one': 1, 'two': 'ii', 'three': 'III', 'four': 'IV'}

アスタリスク2つの正体

イテレータにアスタリスク(*)を付けると、関数の引数としてアンパックできるらしい。

特に辞書に対してアスタリスク2つをつけると、キーワード引数としてアンパックできる。

some_list = ['aaa', 'a', 'aaaa', 'aaaaa', '']
option = {
    'key':len,
    'reverse':True
}
some_list.sort(**option)
print(some_list)
# ['aaaaa', 'aaaa', 'aaa', 'a', '']

この例では、並び替えの基準(key)と昇順/降順(reverse)を辞書で定義して、sort()関数のキーワード引数にアンパックしている。

ちなみに、アスタリスク1つだと、辞書のキーのみがアンパックされる。(リストの場合と同様の動きになる。)

option = {
    'key':len,
    'reverse':True
}
print(*option)
# key reverse
option_list = ['key', 'reverse']
print(*option_list)
# key reverse

追記:Python3.9以降の場合

3.9以降では上記のような複雑なことせずに、論理和の演算子|を使ってとても簡単に実装できるようです!
@shiracamus さんに教えていただきました!

d1 = {'one':1, 'two':2}
d2 = {'two':'ii', 'three':'iii'}

# Case1: 片方の辞書にもう片方を追加する (上書き)
d1 |= d2
print(d1)
# {'one': 1, 'two': 'ii', 'three': 'iii'}

# Case2: 2つの辞書を結合した新しい辞書を生成する
d3 = d1 | d2
print(d3)
# {'one': 1, 'two': 'ii', 'three': 'iii'}

普段触れている業務システムはPython3.6で動いているので、使えないですが、便利や~ :cry:

9
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5