How can I pass a defined dictionary to **kwargs in Python?
Solution 1
There are 4 possible cases:
You call the function using named arguments and you want named variables in the function:
(note the default values)
def buy(orange=2, apple=3):
print('orange: ', orange)
print('apple: ', apple)
buy(apple=4)
# orange: 2
# apple: 4
You call the function using named arguments but you want a dictionary in the function:
then use **dictionaryname
in the function definition to collect the passed arguments
def buy(**shoppinglist):
for name, qty in shoppinglist.items():
print('{}: {}'.format(name, qty) )
buy(apple=4, banana=5)
# banana: 5
# apple: 4
You call the function passing a dictionary but you want named variables in the function:
use **dictionaryname
when calling the function to unpack the dictionary
def buy(icecream=1, apple=3, egg=1):
print('icecream:', icecream)
print('apple:', apple)
print('egg:', egg)
shoppinglist = {'icecream':5, 'apple':1}
buy(**shoppinglist)
# icecream: 5
# apple: 1
# egg: 1
You call the function passing a dictionary and you want a dictionary in the function:
just pass the dictionary
def buy(shoppinglist):
for name, qty in shoppinglist.items():
print('{}: {}'.format(name, qty) )
shoppinglist = {'egg':45, 'apple':1}
buy(shoppinglist)
# egg: 45
# apple: 1
Solution 2
Use **
before fruits argument.
fruits={"apple":10,
"banana":8,
"pineapple":50,
"mango":45
}
def market_prices(name, **fruits):
print("Hello! Welcome to "+name+" Market!")
for fruit, price in fruits.items():
price_list = " {} is NTD {} per piece.".format(fruit,price)
print (price_list)
market_prices('Wellcome ', **fruits) #Use **before arguments
Solution 3
You have a typo defining fruits
. It should have been like the following
fruits = {"apple":10,
"banana":8,
"pineapple":50,
"mango":45
}
Solution 4
Acknowledgments to you guys for the quick and useful comments!
While defining a function, if you put **
for your argument, then make sure to put it too when calling it! Otherwise, put neither!
With
**
fruits={"apple":10, "banana":8, "pineapple":50, "mango":45 } def market_prices(name, **fruits): print("Hello! Welcome to "+name+" Market!") for fruit, price in fruits.items(): price_list = " {} is NTD {} per piece.".format(fruit,price) print (price_list) market_prices('Wellcome ', **fruits)
Without
**
fruits={"apple":10, "banana":8, "pineapple":50, "mango":45 } def market_prices(name, fruits): print("Hello! Welcome to "+name+" Market!") for fruit, price in fruits.items(): price_list = " {} is NTD {} per piece.".format(fruit,price) print (price_list) market_prices('Wellcome ', fruits)
codyhsu
Updated on June 06, 2022Comments
-
codyhsu about 2 years
I learned how to pass both
**kwargs
and*args
into a function, and it worked pretty well, like the following:def market_prices(name, **kwargs): print("Hello! Welcome to "+name+" Market!") for fruit, price in kwargs.items(): price_list = " {} is NTD {} per piece.".format(fruit,price) print (price_list) market_prices('Wellcome',banana=8, apple=10)
However in real case, I'd rather pre-defined a dictionary with lots of key&value, so I won't don't have to type in every parameter when calling my function. I have searched online but cannot find a good example or explanation: Here is the code I try to utilize:
fruits:{"apple":10, "banana":8, "pineapple":50, "mango":45 } def market_prices(name, **fruits): print("Hello! Welcome to "+name+" Market!") for fruit, price in fruits.items(): price_list = " {} is NTD {} per piece.".format(fruit,price) print (price_list)
>>> market_prices('Wellcome ', fruits) NameError: name 'fruits' is not defined
-
chepner almost 6 yearsNote that prior to Python 3.6, this would have shown up as a syntax error. Now, it's just an odd-looking variable annotation.
-
Pedro A. Aranda over 2 yearsJust for the sake of completeness, in most cases you will see something like
def market_place(name,**kwargs):
that you use likemarket_place('La Cebada',**fruits)
(PS: La Cebada is one of the historical markets in Madrid ;-) )