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

I can't solve this annoying problem

I have tried many ways to solve this but I keep getting the same errors like Bummer! 'name'.

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!"]

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

def string_factory(values):
    values_list = []
    for name, food in values: 
        values_list.append(template.format(name, food))
    return(values_list)

I have also tried this and get Bummer! list indices must be integers or slices, not str

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

def string_factory(values):
    values_list = []
    for name, food in values: 
        name = values["name"]
        food = values["food"]
        values_list.append(template.format(name, food))
    return(values_list)

3 Answers

Your thinking about it too much just loop through each item and unpack the values.

# One liner

string_factory = lambda v: list(map(lambda kw:  template.format(**kw), v))

# Long example
def string_factory(values):
    return_list = []
    for value in values:
        return_list.append(template.format(**value))

    return return_list

Thank you so much!!! this was driving me crazy. I didn't quite understand how the unpacking thing worked. I was just wondering with the one-liner approach have we covered lambda or maps yet? or did you know this from other tutorials?

Im more of a teacher than student

Josh Bennett
Josh Bennett
15,258 Points

nope, got an error,

couldn't import `string_factory`.

Are you importing string_factory

string_factory = lambda v: list(map(lambda kw:  template.format(**kw), v))

string_factory(values)

# Outputs : 
# ["Hi, I'm Michelangelo and I love to eat PIZZA!", "Hi, I'm Garfield and I love to eat lasagna!"]