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

Sean Yoon
seal-mask
.a{fill-rule:evenodd;}techdegree
Sean Yoon
Full Stack JavaScript Techdegree Student 6,208 Points

Unpacking a list of dictionaries

You've used the string .format() method before to fill in blank placeholders. If you use a placeholder of {food} in the string, then you pass a keyword argument of food to .format(). The {food} placeholder in the string will be replaced with the value of the food keyword argument.

"Hi, I'm {name} and I love to eat {food}!".format(name="Kenneth", food="tacos")

Returns "Hi, I'm Kenneth and I love to eat tacos!"

Complete the favorite_food function below. It accepts a dictionary as an argument. Your function should unpack that dictionary and pass it to the format method as keywords, then return the resulting string.

I've tried every possible ways I could think of, but it just won't work for me. I keep getting an error message that the argument after ** should be a mapping not str. However, I am able to pass this code on my workplace console. What is going on here? Please help.

string_factory.py
dicts = [
    {'name': 'Michelangelo',
     'food': 'PIZZA'},
    {'name': 'Garfield',
     'food': 'lasanga'},
    {'name': 'Walter',
     'food': 'pancakes'},
    {'name': 'Galactus',
     'food': 'worlds'}
]

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

def favorite_food(dicts):
    new_list = []
    for item in dicts:
        new_list.append(template.format(**item))
    return new_list

print(favorite_food(dicts))

1 Answer

Oszkár Fehér
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Oszkár Fehér
Treehouse Project Reviewer

Hi Sean. In this quiz only 6 characters is needed, nothing more. You changed the original code. Inside the format you just unpack the dict

.format(**dict)

and that passes. Happy coding