0
Unpacking dictionary in a function with python
Hello guys. My question is what is the data type of the function argument? Look at it ! Why we give the dictionary in many variable shapes to the function? I need sb to dive in it and make it clear pls #**kwargs is a dictionary #kwargs.items() returns the key:value pairs def display_info(**kwargs): for key, value in kwargs.items(): print(key, ":", value) display_info(name="Alice", age=30, city="New York")
4 odpowiedzi
+ 2
They’re teaching you how **kwargs works in case you ever need it, but it is a specialty tool. I’ve used it more in the past couple of weeks than I had in the years I’ve been writing Python before that.
+ 2
As you seem to have discovered, **kwargs is meant to combine keyword arguments passed to the function into one dictionary, so that each keyword argument need not be set up individually when the function is defined. I’ve mainly found it used where one function is calling another, sometimes in a different language (like the Tk interpreter), that had several options which might change in the future.
+ 2
Wilbur Jaywright thanks bro
What makes me confused is the way we give the keyword args to the function as arguments. Kinda weird
It seems ugly and time consuming to me
0
To answer your question about what the data type:
**kwargs receives arguments as a dictionary (mutable). Inside dictionary key can be int, str, and tuple only. values can be of any data type.
*args receives arguments as a tuple (immutable). Stores any data type.
Also, just a reminder:
**kwargs (keyworded, variable-length argument list)
*args (non-keyworded, variable-length argument list)