[Reprinted] How to efficiently merge two dictionaries in Python is compared in three methods ., Python dictionary
This article Reprinted from: http://www.pythoner.com/13.html
Merging two dictionaries in Python is a common problem. This article will introduce several solutions to merge two dictionaries and compare them.
The intuitive idea is to add the two dictionaries and assign them to the result dictionary. The Code is as follows:
Method 1:
dictMerged1 = dict( dict1.items() + dict2.items() )
However, the Code for merging this method takes a long time and is more efficient:
Method 2:
dictMerged2 = dict( dict1, **dict2 )
This method usesdict()
Factory method (Python2.2 or later ). If the input parameter is another dictionary (dict1), the new dictionary is generated when the factory method is called. The factory method starts from Python2.3 and can be called using the dictionary or keyword parameter dictionary. However, it should be noted that for this call method,dict()
Only one parameter (or a groupname=value
), Instead of accepting another dictionary. Therefore, the following error message is displayed when you use the dict1 and dict2 parameters intuitively:
>>> dictMerged = dict( dict1, dict2 )Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: dict expected at most 1 arguments, got 2
This is why ** dict2 is used in method 2 above.If you are familiar with C, it should be noted that * Does not mean pointers. This is the method of variable-length function parameters in Python (see the following for more information about variable-length function parameters ). Here, ** indicates a variable-length function parameter based on the dictionary.
Method 2 executes the code in method 3, that is, copy dict1 to dictMerged, andupdate()
Operation:
dictMerged3 = dict1.copy()dictMerged3.update( dict2 )
This built-in method is used for the first copy operation.copy()
The replication method is the same as the replication result in method 2. But according to Section 7.3.2 of Core Python Programming (2nd edition), a new dictionary is generated from an existing dictionary.dictNew = dict( dictOld )
More built-in MethodsdictNew = dictOld.copy()
It will be slower, so it is recommended to usecopy()
Method.
Therefore, from these methods, method 3 is the most efficient and the code is easier to read.
Variable-length Python function parameters
During programming, we may encounter a problem where the number of function parameters is not fixed. In this case, we need to use variable-length function parameters to implement our functions. In Python, there are two variable-length parameters: tuples (non-Keyword parameters) and dictionaries (keyword parameters ). The call method is as follows:func( *tuple_grp_nonkw_args, **dict_grp_kw_args )
The following describes the two variable-length parameters in detail.
1. Variable Length Parameter
When a function call includes a variable length parameter * tuple_grp_nonkw_args, other parameters except the previous fixed position parameter and keyword parameter will be inserted into a tuples for access in order, this is the same as varargs in C.
Assume that there is such a function (positional_arg is a standard call parameter with fixed locations, and keyword_arg is a keyword parameter ):
Example:
def foo( positional_arg, keyword_arg='default', *tuple_arg ): print "positional arg: ", positional_arg print "keyword_arg: ", keyword_arg for each_additional_arg in tuple_arg: print "additional_arg: ", each_additional_arg
We use some examples to learn how it works:
>>> foo(1)positional arg: 1keyword_arg: default >>> foo(1, 2)positional arg: 1keyword_arg: 2 >>> foo(1, 2, 3)positional arg: 1keyword_arg: 2additional_arg: 3
>>> foo(1,2,3,4,5,6)positional arg: 1keyword_arg: 2additional_arg: 3additional_arg: 4additional_arg: 5additional_arg: 6>>> foo(1,2,(3,4,5,6))positional arg: 1keyword_arg: 2additional_arg: (3, 4, 5, 6)
2. variable-length dictionary Parameters
Since the keyword parameter is allowed in Python, there should also be a way to implement the variable length parameter of the keyword, which is the variable length parameter of the dictionary.
In the variable-length dictionary parameter, additional keyword parameters are placed in a dictionary for use. In the dictionary, the key is the parameter name and the value is the corresponding parameter value. It indicates a parameter that starts with ** at the end of the function parameter, for example, ** dict_grp_kw_args. (It should be noted that ** it is overloaded to avoid confusion with power operations .)
The following is an example function of variable-length dictionary parameters:
def foo( positional_arg, keyword_arg='default', **dict_arg ): print "positional arg: ", positional_arg print "keyword_arg: ", keyword_arg for each_dict_arg in dict_arg.keys(): print "dict_arg: %s=>%s" % ( each_dict_arg, str( dict_arg[each_dict_arg] ) )
The following is a demo result:
>>> foo(1, 2, a="b")positional arg: 1keyword_arg: 2dict_arg: a=>b
3. Note
The complete expression of a function call is:
func( positional_args, keyword_args, *tuple_grp_nonkw_args, **dict_grp_kw_args )
All parameters are optional during use, but note the following:The positions of the above four parameters cannot be changed!
4. Extension: Variable Length Parameter in C Language
As an artist, I have never known that the C language also has variable parameters until it is translated into "C and pointer" in "Pointers on C" (People's post and telecommunications Press) see the relevant content (section 7.6 ).
4.1 stdarg macro
In C, variable parameters are implemented through the stdarg macro, which is part of the standard library. This header file declares a typeva_list
And three macrosva_start
,va_arg
,va_end
. We can declare a variable of the va_list type and use it with three macros to access the parameter values.
The following is an example function for calculating the average values of multiple values:
// The following is an example function for calculating the average values of multiple values: # include <stdarg. h> float avg (int n ,...) {va_list var_arg; float sum = 0; // prepare to access the variable length parameter va_start (var_arg, n); // Add the value from the variable length parameter list for (I = 0; I <n; I + = 1) {sum + = va_arg (var_arg, int);} // The variable length parameter va_end (var_arg); return sum/n ;}
The...
As a parameter placeholder, it indicates some parameters with unknown quantity and type.
The function declares that a va_list variable var_arg is used to access the uncertain part of the parameter list. This variable is initialized by calling va_start. The first parameter is the name of the va_list variable, and the second parameter is the last parameter with a name before the placeholder. During initialization, The var_arg variable points to the first parameter in the variable parameter.
Va_list includes two parameters. The first parameter is the va_list variable, and the second parameter is the type of the next parameter. In this example, we assume that all input data is an integer type, so the values are set to int type. In some cases, the type of the next parameter is determined by the previous parameter.
Finally, call va_end to end the access to the variable length parameter.
4.2 restrictions and precautions
Variable parameters are accessed from start to end, that is, they can end after several parameters are accessed,NoAccess the intermediate parameters at the beginning.
In addition, because the variable parameters do not have a prototype, the default function type is upgraded for the values passed to the function as variable parameters.
From the call of va_start, we can see that if variable parameters are used, there must be at least one definite parameter; otherwise, va_start cannot be used.
There are two basic restrictions on these macros: first, the number of actually existing parameters cannot be determined; second, the parameter type cannot be determined.
It should also be noted that once the type of the next parameter is wrong in use, the consequences may be unimaginable.
Python combines two dictionaries into one.
Dict1 = {'1': ('A', 'B', 'C', 'D'), '2': ('F', 'w ', you probably haven't run the content in python at all, have you? Let's see the two dictionaries I have changed.
Combine the two dictionaries in python
Dict1 = {'1': ('A', 'B', 'C', 'D'), '2': ('F', 'w ', 'M'), '3' :( 'P', 'l', 'w ')}
Dict2 = {'1': ('B', 'w', 'q'), '2' :( 'I', 'z', 'M '), '3' :( 'P', 'w', 'O ')}
Dict = {}
For key in dict1.keys ():
Dict [key] = list (dict1 [key])
For key in dict2.keys ():
If dict. has_key (key ):
# Append
For v in dict2 [key]:
If not v in dict [key]:
Dict [key]. append (v)
Else:
Dict [key] = list (dict2 [key])
Print dict