Complex Customization
The Archmage asks Hoppy to build a new type of Magic Golem.
These Golems are complex, and customer requests vary wildly:
Some want material="Iron", others want weapon="Sword", some want height=5, and some even want name="Bob".
If we listed every possible parameter on the blueprint, the list would be a mile long!
The Keyword Vault (**kwargs)
Add two stars ** before a parameter name, and it becomes a vault that can hold any amount of Labeled Data (technically called a Dictionary).
def build_golem(**options):
print("Order Config:")
for key, value in options.items():
print(key + ": " + str(value))
Now you can call it with any label=value pairs:
build_golem(material="Wood", type="Guard")build_golem(name="Bob", power=9000, color="Red")
Your Mission
Create a function named configure_robot that takes **specs.
Inside, print("Robot Specs:"), then loop through specs.items() to print all configuration items.
Call the function with these specs: type="Battle", cpu="M1", armor="Titanium".
In a function definition:
- Regular args (x)
- Default args (y=1)
- *args (The Box)
- **kwargs (The Vault) kwargs must ALWAYS be last!
Suggested SolutionExpandCollapse
def configure_robot(**specs):
print("Robot Specs:")
for part, model in specs.items():
print(part + ": " + model)
configure_robot(type="Battle", cpu="M1", armor="Titanium")Advanced TipsWant more? Click to expandClick to collapse
F. Bridge to Reality
- Keyword Vault = Keyword Arguments, often named
kwargs. - Double Star ()** = Dictionary Unpacking.
- This is one of Python's superpowers. Many complex libraries (like plotting with Matplotlib or querying databases in Django) rely heavily on
**kwargsto let users pass optional configurations without changing the function signature.