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

Samuel Pitt
Samuel Pitt
3,032 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.

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

1 Answer

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 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.

Cheers

Alex