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

Can someone help me understand this error "TypeError: 'int' object is not subscriptable"

Part of my problem is that I don't think I fully understand / visualize what the output would look like in the end if it was printed. What am I doing wrong?

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}!"

def string_factory(dicts, string):
  for item in range(0, len(dicts)):
    values = item[dicts]
    single_dict = string.format(**values)
    print(single_dict)

string_factory(dicts, string)

1 Answer

Dan Johnson
Dan Johnson
40,532 Points

With your loop defined as:

for item in range(0, len(dicts)):

item will be assigned an integer each iteration, so if you were able to look at it in the first iteration it would look like this:

# TypeError
values = 0[dicts]

Here's an outline for building the string_factory function:

def string_factory(dicts, string):
  # Create a list to hold all the formatted strings

  # For each dictionary in the list
    # Call format on the string, unpacking the current dictionary for the arguments
    # Append the formatted string to the formatted strings list

  # Return the formatted strings list

Edit: Here's an example of the output if it helps:

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!

This was the code that produced it:

for message in string_factory(dicts, string):
    print(message)