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

3695 views python
5

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!

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

0

It is a Extended Iterable Unpacking.

>>> a, *b, c = range(5)
>>> a
0
>>> c
4
>>> 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?

JD

Please login first before posting an answer.