首页 > 解决方案 > 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!

标签: pythondictionaryiterable-unpacking

解决方案


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.


推荐阅读