如何在Python中将已定义的字典传递给** kwargs? [英] How can I pass a defined dictionary to **kwargs in Python?
问题描述
这是我第一次在这里发帖.希望我能得到很好的建议:)我学习了如何将 ** kwargs
和 * args
都传递给函数,并且效果很好,如下所示:
This is my first time posting here. Hopefully I can get nice advice:)
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:/ Could you give me some advice? 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:未定义名称水果"
NameError: name 'fruits' is not defined
非常感谢您!:)
推荐答案
有 4 种可能的情况:
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
您使用命名参数调用该函数,但是您希望在该函数中使用字典:
然后在函数定义中使用 ** dictionaryname
来收集传递的参数
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
您通过字典调用该函数,但是您希望在该函数中使用命名变量:
调用函数以解压缩字典时,请使用 ** dictionaryname
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
这篇关于如何在Python中将已定义的字典传递给** kwargs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!