Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 merge 2 dictionaries into a third one, and the above expression accomplishes the task just fine. I am interested in the ** operator and what exactly is it doing to the expression. I thought that ** was the power operator and haven't seen it used in the context above yet.

The full snippet of code is this:

>>> d1 = {'a': 1, 'b': 2} >>> d2 = {'c': 3, 'd': 4} >>> d3 = dict(d1, **d2) >>> print d3 {'a': 1, 'c': 3, 'b': 2, 'd': 4} 
like image 394
λ Jonas Gorauskas Avatar asked Feb 12 '10 23:02

λ Jonas Gorauskas


People also ask

What does -> dict mean in Python?

Definition and Usage The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.

What is dict used for?

Dictionary. Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and do not allow duplicates. As of Python version 3.7, dictionaries are ordered.

What is a dict attribute?

AttrDict , Attribute Dictionary, is the exact same as a python native dict , except that in most cases, you can use the dictionary key as if it was an object attribute instead. This allows users to create container objects that looks as if they are class objects (as long as the user objects the proper limitations).

What is dict in Python with example?

Dictionaries are optimized to retrieve values when the key is known. The following declares a dictionary object. Example: Dictionary. capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"} Above, capitals is a dictionary object which contains key-value pairs inside { } .


1 Answers

** in argument lists has a special meaning, as covered in section 4.7 of the tutorial. The dictionary (or dictionary-like) object passed with **kwargs is expanded into keyword arguments to the callable, much like *args is expanded into separate positional arguments.

like image 128
Thomas Wouters Avatar answered Sep 17 '22 16:09

Thomas Wouters