如何在 Python 中将定义的字典传递给 **kwargs?

cod*_*hsu 11 python dictionary function keyword-argument

这是我第一次在这里发帖。希望我能得到好的建议:) 我学会了如何将**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)
Run Code Online (Sandbox Code Playgroud)

然而,在实际情况下,我宁愿预先定义一个包含大量键值的字典,这样我就不必在调用我的函数时输入每个参数。我在网上搜索过,但找不到好的例子或解释:/你能给我一些建议吗?这是我尝试使用的代码:

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)
Run Code Online (Sandbox Code Playgroud)

NameError:未定义名称“水果”

非常感谢!:)

xdz*_*ze2 20

有4种可能的情况:

您使用命名参数调用函数,并且希望在函数中使用命名变量:(
注意默认值)

def buy(orange=2, apple=3):
    print('orange: ', orange)
    print('apple: ', apple)

buy(apple=4)
# orange:  2
# apple:  4
Run Code Online (Sandbox Code Playgroud)

您使用命名参数调用函数,但您希望函数中有一个字典
然后**dictionaryname在函数定义中使用以收集传递的参数

def buy(**shoppinglist):
    for name, qty in shoppinglist.items():
        print('{}: {}'.format(name, qty) )

buy(apple=4, banana=5)
# banana: 5
# apple: 4
Run Code Online (Sandbox Code Playgroud)

您调用传递字典的函数,但您希望在函数中 使用命名变量:在调用函数以解压字典时使用
**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
Run Code Online (Sandbox Code Playgroud)

你叫传递函数的字典,你想要一本字典的功能:
只需把字典

def buy(shoppinglist):
    for name, qty in shoppinglist.items():
        print('{}: {}'.format(name, qty) )

shoppinglist = {'egg':45, 'apple':1}
buy(shoppinglist)
# egg: 45
# apple: 1
Run Code Online (Sandbox Code Playgroud)


kri*_*hna 12

**在水果参数之前使用。

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
Run Code Online (Sandbox Code Playgroud)