Python: Unpack Dictionary (asterisk)

By Xah Lee. Date: .

Unpack dict to function arguments (**)

turn dictionary into arguments for function call, as keyword arguments. each dictionary pair is turned into key value pair (key=value).

def ff(aa, bb):
    print(aa, bb)

xdict = {"aa": 3, "bb": 4}

# Equivalent to ff(aa=3, bb=4)
ff(**xdict)
# 3 4
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'

Merg dictionaries (**)

xx = {"dog": 3, "cat": 4}
yy = {"cat": 9, "bird": 5}

zz = {**xx, **yy}

print(zz)
# {'dog': 3, 'cat': 9, 'bird': 5}

Unpack keys (*)

use single asterisk (*) to unpack keys, into array, or variables, or function arguments.

# unpact dictionary keys into array
xdict = {"x": 1, "y": 2}
keys = [*xdict]
print(keys)
# ['x', 'y']
# unpact dictionary keys into variables
xdict = {"x": 1, "y": 2}
a, b = [*xdict]
print(a, b)
# x y
# unpact dictionary keys into function arguments
xdict = {"x": 1, "y": 2}

def f(a, b):
    return [a, b]

print(f(*xdict))
# ['x', 'y']