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 (Retired) Dictionaries String Formatting with Dictionaries

Michael Todisco
Michael Todisco
2,790 Points

Python Collections: strings.py Task 1 of 1 Help!

Can't figure this one out please help!

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

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

def string_factory(dicts, string):
  return string.format(**dicts)

2 Answers

Keerthi Suria Kumar Arumugam
Keerthi Suria Kumar Arumugam
4,585 Points

In your code, "dicts" is a list of dictionaries. Ultimately, it is a list. You cannot use ** on a list. You need to take the dictionaries out of the list and apply them to your string iteratively. Please see the modified code below.

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

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

def string_factory(dicts, string):
    string_list = []
    for item in dicts:
        string_list.append(string.format(**item))

    return string_list

print(string_factory(dicts,string))
Georgi Koemdzhiev
Georgi Koemdzhiev
12,610 Points

Since the question asks for just one function parameter the answer from >Keerthi Suria Kumar Arumugam can be converted to that:

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

def string_factory(values):
    output_string = []
    for d in values:
        output_string.append(template.format(**d))
    return output_string