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

Brent Capuano
Brent Capuano
949 Points

Help on this

Having trouble with this. i put both my tries on the board. But i used them each separately. neither are correct
def favorite_food(dict):
    return "Hi, I'm {} and I love to eat {}!".format(name, food)

favorite_food(**{"name": "kenneth", "food": "tacos})

def favorite_food(name=None, food=None):
    return "Hi im {} and i like to eat {}".format(name, food)

favorite_food(**{"name": "you", "food": "pumpkin"})

1 Answer

Louise St. Germain
Louise St. Germain
17,946 Points

Hi Brent,

Glad to see you've been trying this out - dictionary unpacking can be pretty mind-bending and you're definitely not alone in struggling with it.

Better to just start from scratch with the original code given in the challenge:

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

One thing the challenge doesn't really mention explicitly (but probably should) is that the dictionary you're getting as an argument to favorite_food contains the two key-value pairs you need: one that has name as the key and value of someone's name, and the other has food as key and some sort of food as value.

The code they give you is OK - no need to modify/delete any of what's already been written. Just keep in mind that inside this function, you have a variable called dict that contains a dictionary. This is fine. The focus of the challenge is what's happening with the format method. We just need to sort out its argument(s) - which shouldn't be empty!

Because the curly brackets now contain variable names, i.e., {name} and {food} instead of being empty, we're saying to the format method, hey, you can expect us to pass you the two keyword arguments you'll need in order to fill in the blanks: they will be called name and food.

Now all we need to do is unpack dict inside the format method, which will turn the dict's key-value pairs into the keyword arguments that the format method is expecting. The format for unpacking is **dict.

See if you can figure out the challenge now (hint, if you need to type more than six characters to solve the challenge, you're doing too much work! ;-)). I hope some of this helped!