Search code examples
pythondictionarypackingargument-unpacking

Packing and unpacking dictionary


Obviously I am missing something very easy here but I cannot get the answer.

The question is why the code:

def func1(arg1, *arg2):
    print arg1
    print arg2
arg1=1
arg2 = [1,2,3]
func1(arg1, *arg2)

gives 1 (1, 2, 3)

while

def func2(arg1, **arg2):
    print arg1
    print arg2
arg1=1
arg2 = {'arg2_1':1,'arg2_2':2,'arg2_3':3}
func2(arg1, **arg2)

gives 1 {} instead of 1 {'arg2_1':1,'arg2_2':2,'arg2_3':3}.

How can I pack and unpack the dictionary without having to write all of it's elements neither on the function definition nor on the function call? (In the real case the dictionary has a lot of elements and is defined by comprehension.)


Solution

  • Actually it does. Using python 2.7.12:

    >>> def func2(arg1, **arg2):
    ...     print arg1
    ...     print arg2
    ...
    >>> arg1=1
    >>> arg2 = {'arg2_1':1,'arg2_2':2,'arg2_3':3}
    >>> func2(arg1, **arg2)
    1
    {'arg2_1': 1, 'arg2_3': 3, 'arg2_2': 2}