pass multiple dictionaries to a function as an argument

13,815

Solution 1

If you just want to take two dictionaries as separate arguments, just do

def test(SP, CP):
    print SP.keys(),CP.keys()

test(SP, CP)

You only use ** when you want to pass the individual key/value pairs of a dictionary as separate keyword arguments. If you're passing the whole dictionary as a single argument, you just pass it, the same way you would any other argument value.

Solution 2

When you want to pass two different dictionaries to a function that both contains arguments for your function you should first merge the two dictionaries.

For example:

dicA = {'spam':3, 'egg':4}
dicB = {'bacon':5, 'tomato':6}

def test(spam,tomato,**kwargs):
    print spam,tomato

#you cannot use:
#test(**dicA, **dicB)

So you have to merge the two dictionaries. There are several options for this: see How to merge two Python dictionaries in a single expression?

dicC = dicA.copy()
dicC.update(dicB)

#so now one can use:
test(**dicC)

>> 3 6

Solution 3

You can combine both dictionaries (SP and CP) in a single one using the dict constructor.

test(**dict(SP,**CP))

Solution 4

Why it doesn't work:

In Python the "**" prefix in the arguments is to make one argument capture several other ones. For example:

SP = {'key1': 'value1','key2': 'value2'}

def test(**kwargs):              #you don't have to name it "kwargs" but that is
    print(kwargs)                #the usual denomination


test(**SP)
test(key1='value1', key2='value2')

The two call on the test function are exactly the same

Defining a function with two ** arguments would be ambiguous, so your interpreter won't accept it, but you don't need it.

How to make it work:

It is not necessary to use ** when working with normal dictionary arguments: in that case you can simply do:

SP = {'key1': 'value1','key2': 'value2'}
CP = {'key1': 'value1','key2': 'value2'}

def test(SP,CP):
    print(SP)
    print(CP)

test(SP,CP)

Dictionaries are objects that you can directly use in your arguments. The only point where you need to be careful is not to modify directly the dictionary in argument if you want to keep the original dictionnary.

Share:
13,815
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin about 2 years

    I have two dictionaries:

    SP = dict{'key1': 'value1','key2': 'value2'}
    CP = dict{'key1': 'value1','key2': 'value2'}
    

    I have a function that would like to take those two dictionaries as inputs, but I don't know how to do that.

    I'd tried:

    def test(**SP,**CP):
        print SP.keys(),CP.keys()
    
    test(**SP,**CP)
    

    The real function will be more complicated with lots of modification of two dictionaries. But the simple test function doesn't work for me :(