表达式“dict(d1, **d2)”中的“**”是什么意思?
我对下面的 python 表达式很感兴趣:
d3 = dict(d1, **d2)
任务是将两个字典合并到第三个字典中,上面的表达式很好地完成了任务。我对 ** 运算符以及它对表达式到底做了什么感兴趣。我认为 ** 是幂运算符,但尚未在上面的上下文中看到它的使用。
完整的代码片段是这样的:
>>> d1 = {'a': 1, 'b': 2}
>>> d2 = {'c': 3, 'd': 4}
>>> d3 = dict(d1, **d2)
>>> print d3
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
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}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
参数列表中的
**
具有特殊含义,如 教程第 4.7 节。通过**kwargs
传递的字典(或类字典)对象被扩展为可调用的关键字参数,就像*args
被扩展为单独的位置参数一样。**
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.** 将字典变成关键字参数:
变成:
The ** turns the dictionary into keyword parameters:
Becomes:
在Python中,任何函数都可以接受带有*的多个参数;
或多个带 ** 的关键字参数。
接收端示例:
调用端示例(感谢 Thomas):
In Python, any function can accept multiple arguments with *;
or multiple keyword arguments with **.
Receiving-side example:
Calling-side example (thanks Thomas):
还值得一提的是 dict 构造函数的机制。它采用初始字典作为其第一个参数,并且还可以采用关键字参数,每个关键字参数代表要添加到新创建的字典中的新成员。
It's also worth mentioning the mechanics of the dict constructor. It takes an initial dictionary as its first argument and can also take keyword arguments, each representing a new member to add to the newly created dictionary.
您已得到 ** 接线员的答复。这是添加字典的另一种方法
you have got your answer of the ** operator. here's another way to add dictionaries
该运算符用于解压参数列表:
http://docs.python.org/tutorial/controlflow.html#解包参数列表
That operator is used to unpack argument list:
http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists