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

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