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

Please tell me what I did wrong. I finally got the output I was expecting but it's wrong :(

I put a for loop of the list of dictionaries, then used each value of x as my reference to the dictionary keys so I can format the text {name} and {food} and append it to the new_list, then finally return the new list, like it said. I tested it on the shell and got exactly what was on the output of the example.

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!"]
new_list = []
def string_factory(list_of_dictionary):
    for x in list_of_dictionary:
        new_list.append("Hi, I'm {name} and I love to eat {food}".format(name=x["name"], food=x["food"]))
    return new_list



template = "Hi, I'm {name} and I love to eat {food}!"

1 Answer

Manish Giri
Manish Giri
16,266 Points

I'm assuming they want you to use ** for unpacking. This is my working code -

template = "Hi, I'm {name} and I love to eat {food}!"

def string_factory(ldict):
    res = []
    for i in ldict:
        res.append(template.format(**i))
    return res

Thank you it worked :). They are so specific for answers gosh lol

Manish Giri
Manish Giri
16,266 Points

Glad you got it. Here's the same code (cleaned up a bit) using list comprehension -

template = "Hi, I'm {name} and I love to eat {food}!"

def string_factory(ldict):
    return [template.format(**i) for i in ldict]