这是我第一次在这里发帖。希望我能得到好的建议:)
我学会了如何同时通过 **kwargs
和 *args
变成一个函数,它运行得很好,如下所示:
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)
但是在实际情况下,我宁愿预先定义一个包含大量键和值的字典,这样在调用我的函数时就不必输入每个参数。我在网上搜索过,但找不到一个很好的例子或解释:/你能给我一些建议吗?这是我尝试使用的代码:
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:未定义名称“水果”非常感谢!:)
最佳答案
有4种可能的情况:
您使用 调用该函数命名参数 你想要 命名变量 在函数中:
(注意默认值)
def buy(orange=2, apple=3):
print('orange: ', orange)
print('apple: ', apple)
buy(apple=4)
# orange: 2
# apple: 4
您使用 调用该函数命名参数 但你想要 一本字典在函数中:
然后使用
**dictionaryname
在函数定义中收集传递的参数def buy(**shoppinglist):
for name, qty in shoppinglist.items():
print('{}: {}'.format(name, qty) )
buy(apple=4, banana=5)
# banana: 5
# apple: 4
你调用函数传递 一本字典但你想要 命名变量 在函数中:
使用
**dictionaryname
调用函数解压字典时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
你调用函数传递 一本字典你想要 一本字典在函数中:
只是通过字典
def buy(shoppinglist):
for name, qty in shoppinglist.items():
print('{}: {}'.format(name, qty) )
shoppinglist = {'egg':45, 'apple':1}
buy(shoppinglist)
# egg: 45
# apple: 1
关于python - 如何在 Python 中将定义的字典传递给 **kwargs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51751929/