python arguments *args and **args ** is for dictionaries, * is for lists or tuples.

时间:2023-05-17 15:41:02

below is a good answer for this question , so I copy on here for some people need it

By the way, the three forms can be combined as follows: def f(a,*b,**c):

All single arguments beyond the first will end up with the tuple b, and all key/value arguments will end up in dictionary c.

For example, f(1,2,3,4,5,d=6,e=7,f=8) should put 1 in a, (2,3,4,5) in b, and {‘d’:6,’e':7,’f':8} in c.

Let’s see if it does. Let’s define f first:

>>> def f(a,*b,**c):print a,b,c

Now, let’s call the function:

>>> f(1,2,3,4,5,d=6,e=7,f=8)

1 (2, 3, 4, 5) {‘e’: 7, ‘d’: 6, ‘f’: 8}

test(x)

test(*x)

test(**x)

>>> x=(1,2,3)

>>> test(x)

Traceback (most recent call last): File “”, line 1, in ?

TypeError: test() takes exactly 3 arguments (1 given)

Again, as expected. We fed a function that expects 3 arguments with only one argument (a tuple with 3 items), and we got an error.

If we want to use the items in the sequence, we use the following form:

>>> test(*x)

1 2 3

There, x was split up, and its members used as the arguments to test. What about the third form?

>>> test(**x)

Traceback (most recent call last): File “”, line 1, in ?

TypeError: test() argument after ** must be a dictionary

It returned an error, because ** always refers to key/value pairs, i.e., dictionaries.

Let’s define a dictionary then:

>>> x={‘a’:1,’b':2,’c':3}

>>> test(**x) 1 2 3

>>> test(*x)

a c b

Ok. The first call passed on the values in the dictionary.

The second call passed on the keys (but in wrong order!).

Remember, ** is for dictionaries, * is for lists or tuples.