What does single(not double) asterisk * means when unpacking dictionary in Python?

3689 views 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?


answered question

Single * unpacking grabs the keys, so it's adding 1 and 3. With double ** it's trying to call foo(1=2, 3=4) which doesn't make any sense. Keyword arguments must be a valid identifier.

1 Answer


It is a Extended Iterable Unpacking.

>>> a, *b, c = range(5)
>>> a
>>> c
>>> b
[1, 2, 3]

As you can see in the example it allows specifying a "catch-all" name which will be assigned a list of all items not assigned to a "regular" name.

In your case '*' unpacks the keywords only. '**' unpacks as foo(key1:value1, key2:value2). Learn more here.

posted this

Have an answer?


Please login first before posting an answer.