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

natalie fairbourne
natalie fairbourne
1,466 Points

Unpacking Challenge, how do you unpack within a list of dictionaries?

I am at a total loss for the challenge. I don't know how to unpack each dictionary on the list and I don't know if my code is even in the ball park.

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}!"
new_list=[]
def string_factory(dict_list):
    for a in dict_list:
        if 'name' and 'food' in a:
            new_list.append(template.format(name,food))
            print(new_list)

string_factory([**{"name": "Michelangelo", "food": "PIZZA"},{"name": "Garfield", "food": "lasagna"}])   

Hi Natalie,

I'll just provide how to iterate through a list of dict's. I think with that you can solve it! Also remember you need to return the new list.

list_of_dicts = [{"name": "James", "food": "banana"}, {"name": "natalie", "food": "apple"}]
for dicts in list_of_dicts:
    print("Name: {name} \nFood: {food}".format(**dicts))

Hope that helps!

natalie fairbourne
natalie fairbourne
1,466 Points

Thanks James! I figured it out with your help.

1 Answer

Awesome, nice one!

Hi Natalie,

I'll just provide how to iterate through a list of dict's. I think with that you can solve it! Also remember you need to return the new list.

list_of_dicts = [{"name": "James", "food": "banana"}, {"name": "natalie", "food": "apple"}]
for dicts in list_of_dicts:
    print("Name: {name} \nFood: {food}".format(**dicts))

Hope that helps!