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 trialSarah Burgart
5,159 PointsHow to unpack dict in function and then use values from it in .format()?
How to unpack dict in function and then use values from it in .format()? I found some answers from a year ago, but it appears the problem has changed enough that it doesn't quite work.
In the video, he only explained how to use the values if you used the ** in calling the function, not how to do it in the function.
Thanks, Sarah
def favorite_food(dict):
return "Hi, I'm {name} and I love to eat {food}!".format(name, food)
2 Answers
Moosa Bonomali
6,297 PointsIf you look at the example mentioned in the challenge;
"Hi, I'm {name} and I love to eat {food}!".format(name="Kenneth", food="tacos")
You provide some key word arguments to the format function. If you are provided with a dictionary, in order to extract the same keyword arguments you the ** operator on the dictionary. So in your case you only need to unpack your dictionary like this;
def favorite_food(dict):
return "Hi, I'm {name} and I love to eat {food}!".format(**dict)
Sarah Burgart
5,159 Pointsoh my goodness, that is so much simpler than all the almost answers I found on other forums and here. thank you