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

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

I think my answer could be better

Challenge accepted my code but I have a feeling it's less that ideal. Is there a better way to iterate through my list?

def string_factory(list, string):
  string_list = []
  for idx in range(len(list)):
    string_list.append(string.format(**list[idx]))
  return string_list
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}!"

2 Answers

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

Hi there,

Your solution is okay, but you could simplify it a bit by not using the range() function. Like such

def string_factory(ls, string):
  string_list = []
  for i in ls:
    string_list.append(string.format(**i))
  return string_list

I believe that makes the code cleaner and easier to read. Cheers.

Hi

another way of doing it.

def string_factory(myList,myString):
  new_list = []
  for dict in myList:
    new_list.append(myString.format(**dict))
  return new_list