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

Richard Li
Richard Li
9,751 Points

String Formatting with key word arguments Challenge

Hi Guys,

Below is my solution, feels pretty excessive but it works I was wondering what is the best way with least code to tackle the problem?

Also, in this scenario, I know that there will be a kwargs called "name" and "food" beforehand so that I can define the 2 separate function to return that 2 value.

In a real world scenario, how would I know what kwargs the input dict will contain?

Thank you very much!

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

def unpack_name(name,food):
    if name:
        return name

def unpack_food(name,food):
    if food:
        return food

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! In the real world, the dictionary you send in will likely have been created somewhere else in your code. In this case, you will likely know the names of the keys even if you might not know the values. Those values could be retrieved from many places including a user, an API, a file, or a database. Your code works, but it essentially says this: if "food" is not null return the value for food. If name is not null return the value for name. But the easiest way to do this is to just unpack the dictionary directly. I feel like you've overthought this a bit.

Here was my solution:

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

Hope this helps! :sparkles:

Richard Li
Richard Li
9,751 Points

Thank you so much for the reply!

With you help, I am now more familiar with the return value of the unpacking!

So whenever u want to return a value for unpacking it has to have 2 asterisk. In this case in front of dict?