** * This article is from Udemy "[Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style](https://www.udemy.com/course/python-beginner/" Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style ")" It is a class notebook for myself after taking the course of. It is open to the public with permission from the instructor Jun Sakai. ** **
keyword_augment_dict
def menu(food='beef', drink='wine'):
print(food, drink)
menu(food='beef', drink='coffee')
result
beef coffee
First, prepare such a sample. Think about when you want to add more than just food and drink.
keyword_augment_dict
def menu(**kwargs):
print(kwargs)
menu(food='beef', drink='coffee')
result
{'food': 'beef', 'drink': 'coffee'}
By prefixing the argument passed to menu
with**
My arguments are made into a dictionary.
keyword_augment_dict
def menu(**kwargs):
for k , v in kwargs.items():
print(k, v)
menu(food='beef', drink='coffee')
result
food beef
drink coffee
I set up to pull the key and value of the created dictionary and print it.
keyword_augment_dict
def menu(**kwargs):
for k , v in kwargs.items():
print(k, v)
d = {
'food': 'beef',
'drink': 'ice coffee',
'dessert': 'ice cream'
}
menu(**d)
result
food beef
drink ice coffee
dessert ice cream
The dictionary created with d
is expanded and passed to each set of key and value bymenu (** d)
.
args
def menu(fruit, *args, **kwargs):
print(fruit)
print(args)
print(kwargs)
menu('banana', 'apple', 'orange', food='beef', drink='wine')
result
banana
('apple', 'orange')
{'food': 'beef', 'drink': 'wine'}
The first banana
is passed to fruit
as a normal argument,
ʻApple and ʻorange
are tupled by being passed to * args
,
beef
and wine
were dictionaryized by ** kwargs
.
args
def menu(fruit, **kwargs, *args):
print(fruit)
print(kwargs)
print(args)
menu('banana', food='beef', drink='wine', 'apple', 'orange')
result
def menu(fruit, **kwargs, *args):
^
SyntaxError: invalid syntax
An error will occur if ** kwargs
comes first and * args
comes after.
If you want to use them at the same time, use them in the order of *
→ **
.
Recommended Posts