简体   繁体   English

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

[英]How can I pass a defined dictionary to **kwargs in Python?

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:希望我能得到好的建议:) 我学会了如何将**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)

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: name 'fruits' is not defined NameError:未定义名称“水果”

Thank you so much!:)非常感谢!:)

There are 4 possible cases:有4种可能的情况:

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

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然后在函数定义中使用**dictionaryname来收集传递的参数

def buy(**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调用函数解压**dictionaryname时使用**dictionaryname 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

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

Use ** before fruits argument.在水果参数之前使用**

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

You have a typo defining fruits .你有一个定义fruits的错字。 It should have been like the following它应该是这样的

fruits = {"apple":10,
       "banana":8,
       "pineapple":50,
       "mango":45
       }

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 ** 1.带**

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 } 2.没有**水果={“苹果”:10,“香蕉”:8,“菠萝”:50,“芒果”: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)

problem solved:))xoxo问题解决了:))xoxo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM