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

Format() argument after ** has to be a mapping, not a list.

What does this error mean? I don't know what other argument to use besides the placeholder argument I'm using.

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

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

def string_factory(my_dict):
    return template.format(**my_dict)

1 Answer

AJ Salmon
AJ Salmon
5,675 Points

You're correct to use unpacking in the argument to .format(), but my_dict is actually a list of dicts, and you can't unpack a list. Use a for loop, that loops through the list of dicts and performs the .format() once for every dict in the list. Unpacking takes the keys and values in the dict and turns them into keyword arguments, so when you do this, it could be illustrated like this:

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

template.format(**{"name": "Garfield", "food": "lasagna"})
#turns into this behind the scenes
template.format(name="Garfield", food="lasagna")

It does this for every key/value pair that it gets, which is one of the things that makes dictionaries so powerful. So again, use a for loop so that it hits every dict in the list, and don't forget that the challenge wants you to return a list of every string that is made inside of the for loop. You'll need an empty list that you can then .append(). Hope this helps!

AJ