How to efficiently implement two dictionary merges in "reprint" Python, comparing three different methods.

Source: Internet
Author: User

This article was reproduced from: http://www.pythoner.com/13.html

The merging of two dictionaries in Python is a more common problem. This article describes several scenarios for implementing two dictionary merges and compares them.

For this problem, the more intuitive idea is to add two dictionaries, assign to the result dictionary, the code is:

Method One:

dictMerged1 = Dict (Dict1.items () + dict2.items ())  

However, the method takes a longer time to merge, and the more efficient code is:

Method Two:

DictMerged2 = Dict (Dict1, **dict2)

This method uses the dict() factory method (Python2.2 or later). If the input parameter is another dictionary (here, Dict1), the factory method is called to generate a new dictionary from the Dict1 copy of the content. The factory method starts with the Python2.3 version and allows the dictionary or keyword parameter dictionary to be accepted for invocation. It should be noted, however, that for this invocation, dict() only one parameter (or a set name=value of variable-length arguments) is accepted, and no other dictionary is accepted. So the intuitive simple way to use Dict1 and dict2 two parameters will prompt the following error:

>>> dictmerged = Dict (Dict1, Dict2) Traceback (most recent call last):  File "<stdin>", line 1, in < Module>typeerror:dict expected at the most 1 arguments, got 2

  

This is why we see the **dict2 used in method 2 above. A friend familiar with C should note that the meaning of this is not a pointer, which is the notation for variable-length function parameters in Python (see below for a variable-length function parameter). Here, * * means a variable-length function parameter based on a dictionary.

Method 2 executes the code as in Method 3 below, which first copies the Dict1 to Dictmerged, performing the update() operation:

DictMerged3 = Dict1.copy () dictmerged3.update (DICT2)

  

For the first step of the copy operation, this use of the built-in method copy() of replication is the same as in Method 2, but according to "Core Python Programming (2nd edition)" As described in section 7.3, 2, the way in which a new dictionary is generated from an existing dictionary is slower than the built-in dictNew = dict( dictOld ) method, so it is recommended to use the method in the dictNew = dictOld.copy() book copy() .

Therefore, in these ways, Method 3 is the most efficient and the code is easier to read.

Python variable-length function parameters

In the course of programming, we may encounter a case where the number of function parameters is not fixed. At this point, we need to use variable-length function parameters to implement our function. In Python, there are two variable-length parameters, namely tuples (non-keyword arguments) and dictionaries (keyword parameters). It is called as follows: the func( *tuple_grp_nonkw_args, **dict_grp_kw_args ) two variable-length parameters are described in detail below.

1. Tuple variable length parameter

When a tuple variable-length parameter *tuple_grp_nonkw_args is included in a function call, the remaining parameters of the previous fixed position parameter and the keyword parameter are inserted sequentially into a tuple for access, which is the same as the function of varargs in the C language.

Suppose there is a function where Positional_arg is a fixed-position standard call parameter, 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

Let's use some examples to see 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 (, (3,4,5,6)) positional arg:  1keyword_arg:  2additional_arg:  (3, 4, 5, 6)

  

  

2. Dictionary variable length parameter

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 dictionary variable-length parameter.

In the dictionary variable length parameter, the extra keyword parameter is put into a dictionary for use. In the dictionary, the key is the parameter name and the value is the corresponding parameter value. It is represented by arguments placed at the end of the function argument, such as **dict_grp_kw_args. (It is important to note that * * is overloaded to not be confused with a power operation.) )

The following is an example function of a dictionary variable-length parameter:

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 representation of a function call is:
func( positional_args, keyword_args, *tuple_grp_nonkw_args, **dict_grp_kw_args )

In the process of use, all parameters are optional, but it should be noted that: the position of the above four parameters is not interchangeable!

4. Extension: variable length parameter in C language

As a person who didn't know how to learn, the C language also has a variable parameter, until in the "pointers on C" (Chinese translation: "C and hands", the people's post and Telecommunications publishing house) see the relevant content (Section 7.6).

4.1 STDARG macro

In the C language, mutable parameters are implemented by Stdarg macros, which are part of the standard library. This header file declares a type va_list and three macros, a va_start va_arg va_end . We can declare a variable of type va_list and use it with three macros to access the value of the parameter.

Here is an example function that calculates the average of multiple values:

Here is an example function that calculates the average 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 values taken from the variable-length argument list for    (i = 0; i < n; i + = 1) {        sum + = Va_arg (var_arg, int);    }     Complete processing variable length parameter    va_end (VAR_ARG);     return sum/n;}

  

Where function parameters are placeholders for ... parameters that represent numbers and types that are not known.

A variable of type va_list is declared in the function Var_arg used to access the indeterminate part of the parameter list. This variable is initialized by calling Va_start, where the first argument is the name of the va_list variable, and the second argument is the last named argument before the placeholder. The initialization process points the VAR_ARG variable to the first parameter in a mutable parameter.

Va_list is used, including two parameters, the first parameter is the va_list variable, the second argument is the type of the next parameter. In this case, the input data is assumed to be integer, so all are set to int, and 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 Limitations and Precautions

Variable parameters are accessed from beginning to end, which can be done after several parameters have been accessed, but the intermediate parameters cannot be accessed from the beginning.

In addition, because there is no prototype for the mutable parameter section, the value passed to the function as a mutable parameter is given the default function type promotion.

As you can see from the Va_start call, you cannot use Va_start if you must have at least one determined parameter using a mutable parameter.

There are two basic limitations to these macros: one is that there is no way to judge the actual number of arguments, and the other is that the parameter type cannot be judged.

It is also important to note that once the type of the next parameter is incorrectly written in use, the consequences can be disastrous.

How to efficiently implement two dictionary merges in "reprint" Python, comparing three different methods.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.