Python Python Collections Dictionaries String Formatting with Dictionaries

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
def favorite_food(dict):
    return "Hi, I'm {name} and I love to eat {food}!".format(**dict)

2 Answers

Chris Freeman
Chris Freeman
Treehouse Moderator 55,474 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!!!

1,311 Points

Super. Thanks Chris. I understand your reponse.