Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (Retired) Dictionaries String Formatting with Dictionaries

Leen Leenaerts
PLUS
Leen Leenaerts
Courses Plus Student 2,367 Points

what's wrong?

?

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

2 Answers

If you open a workspace and add a print to the bottom of your code:

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):
  l = []
  for i in dicts:
    string = string.format(**i)  # line 1 
    l.append(string)             # line 2
    # try to combine line 1 and line 2 into 1 single line.
  return l

# print output
print(string_factory(dicts, string))

Your output is repeating the same line over and over:

["Hi, I'm Michelangelo and I love to eat PIZZA!", "Hi, I'm Michelangelo and I love to eat PIZZA!", "Hi, I'm Michelangelo and I love to eat PIZZA!", "Hi, I'm Michelangelo and I love to eat PIZZA!"]

It should be:

["Hi, I'm Michelangelo and I love to eat PIZZA!", "Hi, I'm Garfield and I love to eat lasanga!", "Hi, I'm Walter and I love to eat pancakes!", "Hi, I'm Galactus and I love to eat worlds!"]