Python: Function call, pass dict or list as args
Pass dict as keyword arguments to function
**xdict
means pass the dictionary as list of keyword arguments.
For example if dict is
{"aa": 3, "bb": 4}
it's passed as
aa=3, bb=4
🛑 warning: error if dictionary contains keys not in function parameter.
# example of unpack a dict for function call def ff(aa, bb): print(aa, bb) xdict = {"aa": 3, "bb": 4} # Equivalent to ff(aa=3, bb=4) ff(**xdict) # 3 4
# example of unpack a dict, that only covers some of the keyword parameters def ff(aa=3, bb=4): print(aa, bb) xdict = {"bb": 9} # Equivalent to ff(bb=9) ff(**xdict) # 3 9
# error if dictionary contain keys not in function parameter def ff(aa=3, bb=4): print(aa, bb) xdict = {"cc": 7} # Equivalent to ff(cc=7) ff(**xdict) # ff(**xdict) # ~~^^^^^^^^^ # TypeError: ff() got an unexpected keyword argument 'cc'
Pass list as positional arguments to function
def ff(aa, bb): print(aa, bb) xlist = [3, 4] # Equivalent to ff(3, 4) ff(*xlist) # 3 4