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

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

string_factory.py
# 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)
        new_value.append(template)

    return new_value

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,428 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.

        name=value['name']
        food=value['food']

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'])
        new_value.append(bobs_your_uncle)
# 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,428 Points

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