The Python Dictionary ** unpack operator
When passing a dictionary to a function, the key-value pairs can be unpacked into keyword arguments in a function call where the dictionary keys match the parameter names of the function.
If the function doesn't exactly specify the dictionary keys in the function's
parameters, Python will throw a TypeError
exception.
Syntax
function(**dictionary)
Example
def myFish(guppies, zebras, bettas): print(f'I have {guppies} guppy fish.') print(f'I have {zebras} zebra fish.') print(f'I have {bettas} betta fish.') fish = { 'guppies': 2, 'zebras' : 5, 'bettas': 10 } myFish(**fish)
Output
I have 2 guppy fish. I have 5 zebra fish. I have 10 betta fish.
Here, the names of parameters of the function match the keys in the dictionary, but that is not necessary. All we need is there to be as many parameters as there are keys in the dictionary.
Notes
The dictionary unpack ** operator is often used with a function that can take any number of parameters. This is one of the most complicated things about Python to wrap one's head around but is very useful for capturing any keyword arguments, not just passing dictionary key-value pairs as arguments.
Example
def myFish(**fish): for name, value in fish.items(): print(f'I have {value} {name}') fish = { 'guppies': 2, 'zebras' : 5, 'bettas': 10 } myFish(**fish)
Output
I have 2 guppies I have 5 zebras I have 10 bettas