Course Content
Intermediate Python Techniques
Intermediate Python Techniques
**kwargs
Now, let's move on to keyword arbitrary arguments
or **kwargs
. The principle of how **kwargs
works is the same as for *args
, but it accepts keyword arguments instead of positional ones. **kwargs
packs information into a dictionary, so we will work with it accordingly.
def personal_info(name, **kwargs): print(f"Name: {name}") for key, value in kwargs.items(): print(f"{key.capitalize()}: {value}") personal_info("Sarah", surname="Conor", son="John") personal_info("Natalie", cats="3", breed="Maine Coon")
The correct order for the arguments is as follows:
- Positional
- Optional
- *args
- **kwargs
def new_func(a, b=0, *args, **kwargs): print(f'a = {a}, b = {b}, args = {args}, kwargs = {kwargs}') new_func(1, 2, 'Love', 'Hope', name='Anna', age=20)
If you want to unpack dictionaries, you need to use **
before the dictionary variable.
Thanks for your feedback!