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

the output is correct, but what is wrong

that is my code , can someone explain to me or if you can suggest any other good way thanks

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}!"
hasil = []
def string_factory(dicts, string):
    for x in dicts:
      makanan = ''
      nama = ''
      for z in x:
          if makanan == '':
              makanan = x[z]
          elif makanan == x[z]:
              makanan = ''
          elif nama == '':
              nama = x[z]

          if nama != '':
              hasil.append(string.format(name=nama,food=makanan))
return hasil

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Try moving the initiation of hasil to inside the function.

Your return statement does not look properly indented. It should be inside the function.

yes worked , but are you have any better code than my code ? i think my code still need improvement to better one ..

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Since the list of dictionaries uses the same key names as the string, you can unpack the dictionary directly in the format() function:

def string_factory(dicts, string):
    hasil = []
    for x in dicts:
        hasil.append(string.format(**x))
    return hasil

Kerja Bagus!

*I had to use Google translate. I hope it's close!