Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Why am I getting an error

its telling me that it couldn't import string factory so what am I doing wrong in this code

# Example:
# values = [{"name": "Michelangelo", "food": "PIZZA"}, {"name": "Garfield", "food": "lasagna"}]
# string_factory(values)
# ["Hi, I'm Michelangelo and I love to eat PIZZA!", "Hi, I'm Garfield and I love to eat lasagna!"]

def string_factory(values):

    template = "Hi, I'm {name} and I love to eat {food}!"
    new_value = []
    for value in values:
        if name and food:
            template.format(name, food)

    return new_value

1 Answer

Chris Freeman
Chris Freeman
Treehouse Moderator 68,094 Points

You have the right idea. There isn't a need to verify that 'name' and 'food' are present. The 'name' and 'food' you are looking for would be keys in the local dict value. As keys, they would be strings. As written, name and food are undefined variables. The correct form would be:

        if 'name' in value  and 'food' in value:

The dict values name and food must be extracted from the dictionary. They are not freely available to use directly.


As for the, append(), only the original template is appended again and again. The format() method returns a new string formatted as requested. Since the format result is not assigned to a variable, the result is lost. Two choices

# assign it a variable
        bobs_your_uncle = template.format(name=value['name'], food=value['food'])
# or use the result directly:
        new_value.append(template.format(name=value['name'], food=value['food'])

Post back if you need more help. Good luck!!

why am I now getting an error that tells me that it couldn't import string_factory?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,094 Points

It means a syntax issue is keeping string_factory from compiling correctly.