What does `**` mean in the expression `dict (d1, ** d2)`?

I am intrigued by the following python expression:

d3 = dict(d1, **d2) 

The task is to combine 2 dictionaries into a third, and the above expression does an excellent job. I'm interested in the ** operator and what exactly does it do with the expression. I thought ** was a power operator and had not yet seen him in the context above.

Full code snippet:

 >>> d1 = {'a': 1, 'b': 2} >>> d2 = {'c': 3, 'd': 4} >>> d3 = dict(d1, **d2) >>> print d3 {'a': 1, 'c': 3, 'b': 2, 'd': 4} 
+40
operators python dictionary syntax set-operations
Feb 12 '10 at 23:57
source share
6 answers

** in the argument lists is of particular importance, as described in the section of section 4.7 of the textbook . The dictionary (or dictionary-like) object passed with **kwargs is expanded into the keyword arguments to the called one, just as *args decomposed into separate positional arguments.

+41
Feb 13 '10 at 0:00
source share

** translation of the dictionary into keywords:

 >>> d1 = {'a': 1, 'b': 2} >>> d2 = {'c': 3, 'd': 4} >>> d3 = dict(d1, **d2) 

becomes:

 >>> d3 = dict(d1, c=3, d=4) 
+12
Feb 13 '10 at 0:01
source share

In Python, any function can take multiple arguments with *; or multiple keyword arguments with **.

An example of a receiving side:

 >>> def fn(**kwargs): ... for kwarg in kwargs: ... print kwarg ... >>> fn(a=1,b=2,c=3) a c b 

Call side example (thanks to Thomas):

 >>> mydict = dict(a=1,b=2,c=3) >>> fn(**mydict) a c b 
+9
Feb 12 '10 at 23:59
source share

Also worth mentioning is the mechanics of the dict constructor. It takes the initial dictionary as the first argument and can also accept keyword arguments, each of which represents a new member to be added to the newly created dictionary.

+3
Feb 13 '10 at 8:53
source share

This statement is used to unpack the argument list: http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists

+1
Feb 13 2018-10-10T00
source share

you have operator response **. here is another way to add dictionaries

 >>> d1 = {'a': 1, 'b': 2} >>> d2 = {'c': 3, 'd': 4} >>> d3=d1.copy() >>> d3.update(d2) >>> d3 {'a': 1, 'c': 3, 'b': 2, 'd': 4} 
+1
Feb 13 '10 at 0:24
source share



All Articles