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)
defbuy(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
defbuy(**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
defbuy(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
defbuy(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
}
defmarket_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:
thank you guys for the quick and useful comment! here i try a few and it works! while defining function, if you put ** for your argument, then make sure to put it too when calling it! otherwise, put neither! 1.with **
fruits={"apple":10,
"banana":8,
"pineapple":50,
"mango":45
}
defmarket_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)
2.without** fruits={"apple":10, "banana":8, "pineapple":50, "mango":45 }
defmarket_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)
problem solved:))xoxo
Post a Comment for "How Can I Pass A Defined Dictionary To **kwargs In Python?"