python/can i pass a defined dictionary to **kwargs?

无人久伴 提交于 2020-05-29 08:05:09

问题


this is my first time posting here. hopefully i can get nice advice:) i have learnt 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 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 say:

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

thank you so much!:)


回答1:


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

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

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



回答2:


You have a typo defining fruits. It should have been like the following

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



回答3:


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



回答4:


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 **

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)

problem solved:))xoxo



来源:https://stackoverflow.com/questions/51751929/python-can-i-pass-a-defined-dictionary-to-kwargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!