Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Dictionaries String Formatting with Dictionaries

eestsaid
eestsaid
1,311 Points

favorite_food challenge, not sure how unpacking works

Below code seems to work but I am unsure as to what is happening when ** dict is passed as an argument in the format string. From this I assume the function is called with values for "name" and "food". Could someone possibly step through what is happening when the function called. Thanks

string_factory.py
def favorite_food(dict):
    return "Hi, I'm {name} and I love to eat {food}!".format(**dict)

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

Under argument in the glossary it says:

A value passed to a function (or method) when calling the function. There are two kinds of argument:

  • keyword argument: an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by **. For example, 3 and 5 are both keyword arguments in the following calls to complex():
complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})
  • positional argument: an argument that is not a keyword argument. Positional arguments can appear at the beginning of an argument list and/or be passed as elements of an iterable preceded by *. For example, 3 and 5 are both positional arguments in the following calls:
complex(3, 5)
complex(*(3, 5))

So when a **dict is declared as a parameter, any dict passed in will be converted to key1=value1, key2=value2,....

Pro tip: don’t use built in type names such as dict, str, list, etc as parameter names. It can cause bad side effects.

Post back if you need more help. Good luck!!!

eestsaid
eestsaid
1,311 Points

Super. Thanks Chris. I understand your reponse.