Python 辞書をマージする

辞書を指定し、すべての数値の合計を計算します。

例1:update()メソッドを使用して、2番目のパラメータを最初のパラメータとマージする

def Merge(dict1, dict2): 
    return(dict2.update(dict1)) 

# 二つの辞書
dict1 = {'a': 10, 'b': 8} 
dict2 = {'d': 6, 'c': 4} 

#  Noneを返す 
print(Merge(dict1, dict2)) 

# dict2はdict1とマージされた

print(dict2)

上記のコードを実行した結果は次のとおりです。

None
{'d': 6, 'c': 4, 'a': 10, 'b': 8}

例2:**を使用して、関数はパラメータを辞書の形式でインポートする

def Merge(dict1, dict2): 
    res = {**dict1, **dict2} 
    return res 
 
# 二つの辞書
dict1 = {'a': 10, 'b': 8} 
dict2 = {'d': 6, 'c': 4} 
dict3 = Merge(dict1, dict2) 
print(dict3)

上記のコードを実行した結果は次のとおりです。

{'a': 10, 'b': 8, 'd': 6, 'c': 4}
Share

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です