Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "**" mean in python? [duplicate]

Possible Duplicate:
What does ** and * do for python parameters?
What does *args and **kwargs mean?

Simple program:

storyFormat = """                                       
Once upon a time, deep in an ancient jungle,
there lived a {animal}.  This {animal}
liked to eat {food}, but the jungle had
very little {food} to offer.  One day, an
explorer found the {animal} and discovered
it liked {food}.  The explorer took the
{animal} back to {city}, where it could
eat as much {food} as it wanted.  However,
the {animal} became homesick, so the
explorer brought it back to the jungle,
leaving a large supply of {food}.

The End
"""                                                 

def tellStory():                                     
    userPicks = dict()                              
    addPick('animal', userPicks)            
    addPick('food', userPicks)            
    addPick('city', userPicks)            
    story = storyFormat.format(**userPicks)
    print(story)

def addPick(cue, dictionary):
    '''Prompt for a user response using the cue string,
    and place the cue-response pair in the dictionary.
    '''
    prompt = 'Enter an example for ' + cue + ': '
    response = input(prompt).strip() # 3.2 Windows bug fix
    dictionary[cue] = response                                                             

tellStory()                                         
input("Press Enter to end the program.")     

Focus on this line:

    story = storyFormat.format(**userPicks)

What does the ** mean? Why not just pass a plain userPicks?

like image 311
DNB5brims Avatar asked Nov 06 '11 15:11

DNB5brims


People also ask

What does duplicate do in Python?

Definition and Usage The duplicated() method returns a Series with True and False values that describe which rows in the DataFrame are duplicated and not.

How do you double a value in a series in Python?

multiply() function perform the multiplication of series and other, element-wise. The operation is equivalent to series * other , but with support to substitute a fill_value for missing data in one of the inputs. Example #1: Use Series.


1 Answers

'**' takes a dict and extracts its contents and passes them as parameters to a function. Take this function for example:

def func(a=1, b=2, c=3):
   print a
   print b
   print b

Now normally you could call this function like this:

func(1, 2, 3)

But you can also populate a dictionary with those parameters stored like so:

params = {'a': 2, 'b': 3, 'c': 4}

Now you can pass this to the function:

func(**params)

Sometimes you'll see this format in function definitions:

def func(*args, **kwargs):
   ...

*args extracts positional parameters and **kwargs extract keyword parameters.

like image 182
Manny D Avatar answered Oct 18 '22 18:10

Manny D