Passing a dictionary to a function as keyword parameters
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Python, use the ** (double-splat) operator to unpack a dictionary as keyword arguments when calling a function: func(**my_dict). Each dictionary key becomes a parameter name and each value becomes the argument. The keys must be strings and must match the function's parameter names (or the function must accept **kwargs). This pattern is widely used for configuration passing, decorator forwarding, and building dynamic function calls.
Basic Usage
The ** operator unpacks the dictionary so that params["name"] becomes name="Alice" and params["greeting"] becomes greeting="Hi".
Mixing Positional and Dictionary Arguments
Using **kwargs to Accept Any Keywords
Forwarding Arguments Between Functions
A common pattern is accepting **kwargs in one function and forwarding them to another:
Merging Dictionaries for Function Calls
Building Dynamic Function Calls
Filtering Dictionary Keys
If the dictionary has keys that do not match the function parameters, you get a TypeError. Filter first:
Common Pitfalls
- Dictionary keys do not match function parameter names: If the dictionary contains a key that is not a valid parameter name and the function does not accept
**kwargs, Python raisesTypeError: unexpected keyword argument. Verify keys match parameter names before unpacking. - Non-string dictionary keys: The
**operator requires all dictionary keys to be strings. A dictionary like{1: "a", 2: "b"}raisesTypeErrorwhen unpacked. Convert keys to strings first if needed. - Passing the same argument twice: If you pass a keyword argument explicitly and it is also in the dictionary, Python raises
TypeError: got multiple values for argument. Remove the key from the dictionary or do not pass it as a separate keyword. - Mutating the original dictionary with
pop()inside the function: Usingkwargs.pop("key")modifies the dictionary in place if it was passed directly. If the caller reuses the dictionary, keys will be missing. Usekwargs.get()for non-destructive access, or unpack a copy. - Confusing
*argswith**kwargs:*unpacks a list/tuple as positional arguments, while**unpacks a dictionary as keyword arguments. Using*on a dictionary unpacks its keys as positional arguments, not key-value pairs.
Summary
- Use
func(**my_dict)to unpack a dictionary as keyword arguments - Dictionary keys must be strings and must match the function's parameter names
- Use
**kwargsin the function signature to accept arbitrary keyword arguments - Merge dictionaries with
{**defaults, **overrides}before unpacking - Filter dictionary keys with
inspect.signaturewhen extra keys are present

