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

18

我学会了如何将**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: name 'fruits' is not defined
4个回答

32

有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

11

在水果参数之前使用**

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

1
为了完整起见,在大多数情况下,您会看到类似于 def market_place(name,**kwargs): 这样的东西,您可以像这样使用 market_place('La Cebada',**fruits)(PS:La Cebada 是马德里历史悠久的市场之一;-)) - Pedro A. Aranda

2

感谢你们快速而有用的评论!

在定义函数时,如果你在参数中使用了**,那么在调用函数时也要确保使用它!否则就都不要使用!

  1. 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)
    
  2. 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)
    

1
你定义 fruits 时有一个拼写错误。应该像以下这样:
fruits = {"apple":10,
       "banana":8,
       "pineapple":50,
       "mango":45
       }

1
请注意,在Python 3.6之前,这将显示为语法错误。现在,它只是一个看起来奇怪的变量注释。 - chepner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接