codyhsu
codyhsu

Reputation: 233

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

Upvotes: 20

Views: 22073

Answers (4)

codyhsu
codyhsu

Reputation: 233

Acknowledgments to you guys for the quick and useful comments!

While defining a 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)
    

Upvotes: 3

xdze2
xdze2

Reputation: 4151

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

Upvotes: 36

Bal Krishna Jha
Bal Krishna Jha

Reputation: 7206

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

Upvotes: 12

Sunitha
Sunitha

Reputation: 12005

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

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

Upvotes: 1

Related Questions