Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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: 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
like image 303
codyhsu Avatar asked Aug 08 '18 16:08

codyhsu


1 Answers

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
like image 108
xdze2 Avatar answered Nov 16 '22 01:11

xdze2