Python Merge Dictionaries

Document 对象参考手册Python3 Examples

Given two dictionaries, merge them into one dictionary.

Example 1: Using the update() method, the second parameter merges into the first parameter.

def Merge(dict1, dict2): return(dict2.update(dict1)) # Two dictionaries dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} # Returns None print(Merge(dict1, dict2)) # dict2 is merged into dict1 print(dict2)

Executing the above code produces the following output:

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

Example 2: Using **, the function imports parameters in the form of a dictionary.

def Merge(dict1, dict2): res = {**dict1, **dict2} return res # Two dictionaries dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} dict3 = Merge(dict1, dict2) print(dict3)

Executing the above code produces the following output:

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

Document 对象参考手册Python3 Examples

Other Extensions