25

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?

Henry Ecker
35.8k19 gold badges48 silver badges67 bronze badges
asked Nov 6, 2011 at 15:48
0

2 Answers 2

57

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

answered Nov 6, 2011 at 15:53
Sign up to request clarification or add additional context in comments.

3 Comments

So, it can take the dictionary key to map back the params, is that right? What is this function/feature called? I found it is very funny and powerful, is this unique for the python ONLY?
@DNB5brims, I believe this is called "destructuring". It is finding its way into other languages such as Javascript (ECMAScript 2015).
Note that the key values of the params dict must match the names of the optional parameters listed in the definition of func, otherwise a TypeError will occur.
5

**means kwargs. here is a good article about it.
read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

answered Nov 6, 2011 at 15:52

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.