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

Code not working

Can someone please tell me 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(dct, st):
  new_list = []
  for l in dct:
    if st in l:
      st.format(**dct)
      new_list.append(st)
  return new_list

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Two things that I see right off the bat

  1. You don't need that if. We want to run this code on every member of the dictionary, not just ones where the string is in the list...if that would even be true (it won't)
  2. Doing st.format(**dct) without assigning it to a variable will make the new string vanish once the operation is complete. You need to assign it to a variable (because strings can't be changed in-place) so you can add it to the list (or just add it to the list directly).

Thanks Kenneth after 2 days of thinking about it, I got it by removing the if and I assigned the formatted string into a variable. Here's my code

def string_factory(lst, st): new_list = [] for dct in lst: new = st.format(**dct) new_list.append(new) return new_list