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

Samuel Pitt
Samuel Pitt
3,019 Points

Having trouble passing in a dictionary to a function, then calling it with keyword placeholders in a printed string!

if anyone knows how to help me with this, it would be much appreciated. I have tried a lot of ways, but none have worked (i did generate some interesting errors though!).

any help appreciated, but a template with explanation would be fantastic.

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

1 Answer

Alex Koumparos
Alex Koumparos
Python Web Development Treehouse Moderator 33,371 Points

Hi Samuel,

The challenge is asking you to "unpack" the dictionary. Packing and unpacking dictionaries is explained in the video immediately prior to this challenge: Packing and Unpacking Dictionaries.

In the teacher's notes for that video, Kenneth provides the following example of unpacking:

>>> my_dict = {'name': 'Kenneth'}
>>> "Hi, my name is {name}!".format(**my_dict)
"Hi, my name is Kenneth!"

Notice how he just passes the name of the dictionary (my_dict) to the format function, prefixing it with the two asterisks.

Hope that points you in the right direction. Let me know if you are still stuck after trying the above approach.