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

Chih-Wei Hsu
Chih-Wei Hsu
11,132 Points

not sure what's wrong with my code

can anyone help me understand what's wrong with my code here for the string_factory challenge? thanks a lot!

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):
  new_list = []
  for i in dicts:
    new_list.append(string.format(**i))
return new_list

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Chih-Wei Hsu, You are Very close. The error is caused by the return indent. Here is your code modified to pass:

def string_factory(dicts, string):
  new_list = []
  for i in dicts:
    new_list.append(string.format(**i))
  return new_list  #<-- return indented to align with for statement

Without indenting return, the function string_factory returned None

Chih-Wei Hsu
Chih-Wei Hsu
11,132 Points

Thanks, Chris. A small bug makes a huge difference !

Hi Chih

loop though the list and then use the name and food keys of the dictionary to populate the new list.

def string_factory(mydicts,mystring):
  new_list= []
  for dic in mydicts:
    new_list.append(mystring.format(name=dic["name"],food=dic["food"]))
  return new_list  
Chih-Wei Hsu
Chih-Wei Hsu
11,132 Points

Thanks, Andreas for providing an alternative solution that I didn't think about.