Merging two dictionaries in Python is a relatively common problem. This article will introduce several solutions to merge two dictionaries and compare them.
For this problem, the more intuitive idea is to add the two dictionaries and assign the value to the result dictionary. The code is:
Python merges the two dictionaries (Method 1 )
dictMerged1 = dict( dict1.items() + dict2.items() )
However, this method takes a long time to merge, and the more efficient code is:
Python merges two dictionaries (Method 2)
dictMerged2 = dict( dict1, **dict2 )
This method uses the dict() factory method (Python 2.2 or above). If the input parameter is another dictionary (here dict1), when the factory method is called, the contents will be copied from dict1 to generate a new dictionary. Starting from Python 2.3, this factory method allows calling a dictionary or keyword argument dictionary.
But it should be noted that for this calling method, dict() only accepts at most one parameter (or a set of variable-length parameters with name=value), and will not accept another dictionary. Therefore, the intuitive method of simply using the two parameters dict1 and dict2 will prompt the following error:
>>> dictMerged = dict( dict1, dict2 ) Traceback (most recent call last): File "", line 1, in TypeError: dict expected at most 1 arguments, got 2
This is why we see that **dict2 is used in method 2 above. Friends who are familiar with C should note that * here does not mean a pointer. This is the way to write variable-length function parameters in Python (see this article for relevant knowledge about variable-length function parameters). Here, ** means dictionary-based variable-length function parameters.
Method 2 executes the code as in Method 3 below, that is, first copies dict1 to dictMerged, and then performs the update() operation:
Python merges two dictionaries (method 3)
dictMerged3 = dict1.copy() dictMerged3.update( dict2 )
For the first step of the copy operation, this copy method using the built-in method copy() is the same as the copy result in method 2, but according to "Core As mentioned in Section 7.3.2 of the book Python Programming (2nd edition), the method of generating a new dictionary from an existing dictionary dictNew = dict(dictOld) is slower than the built-in method dictNew = dictOld.copy(), so the book It is recommended to use the copy() method.
Therefore, from these methods, method 3 is the most efficient and the code is easier to read.
Related recommendations: "Python Tutorial"
The above is the detailed content of How to merge two dictionaries in python. For more information, please follow other related articles on the PHP Chinese website!