python - What does single(not double) asterisk * means when unpacking dictionary in Python?
问题描述
Can anyone explain the difference when unpacking the dictionary using single or double asterisk? You can mention their difference when used in function parameters, only if it is relevant here, which I don't think so.
However, there may be some relevance, because they share the same asterisk syntax.
def foo(a,b)
return a+b
tmp = {1:2,3:4}
foo(*tmp) #you get 4
foo(**tmp) #typeError: keyword should be string. Why it bothers to check the type of keyword?
Besides, why the key of dictionary is not allowed to be non-string when passed as function arguments in THIS situation? Are there any exceptions? Why they design Python in this way, is it because the compiler can't deduce the types in here or something?
Thanks!
解决方案
When dictionaries are iterated as lists the iteration takes the keys of it, for example
for key in tmp:
print(key)
is the same as
for key in tmp.keys():
print(key)
in this case, unpacking as *tmp
is equivalent to *tmp.keys()
, ignoring the values. If you want to use the values you can use *tmp.values()
.
Double asterisk is used for when you define a function with keyword parameters such as
def foo(a, b):
or
def foo(**kwargs):
here you can store the parameters in a dictionary and pass it as **tmp
. In the first case keys must be strings with the names of the parameter defined in the function firm. And in the second case you can work with kwargs
as a dictionary inside the function.
推荐阅读
- javascript - 在简单的 CRUD 应用程序之外构建 Django/React 项目(概念)
- javascript - 关闭模态控制器外部的 ngb-modal
- node.js - IIS/ASP.Net 与 NodeJs/ExpressJS
- wordpress - 如何将“大”添加到 wordpress API 发布数据
- go - delphi/pascal <> golang(异或加密)
- kubernetes - Kubernetes:将 HPA 与来自其他 pod 的指标结合使用
- python - 将目标函数和约束转换为代码
- python - XGBoostError: 检查失败: typestr.size() == 3 (2 vs. 3) : `typestr' 应该是格式
- asp.net - 在 Neoj4Client 中检索关系会导致反序列化异常
- ios - 如何从带有 400 状态码的响应中访问服务器错误响应?