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

Maximilian Richly
Maximilian Richly
4,872 Points

Help!! list indices must be integers or slices, not dict

it says: list indices must be integers or slices, not dict

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):
  list_thing = []
  for item in dicts:
    temp_dict = dicts[item]
    list_thing[item] = string.format(**temp_dict)
  return list_thing

What do you mean?

Maximilian Richly
Maximilian Richly
4,872 Points

ah sorry, what I meant was: i see how using .append works for making the list, but why does it not work when I iterate over item in the for loop when creating list_thing (I hope this is clear)

Maximilian Richly
Maximilian Richly
4,872 Points

ah sorry, what I meant was: i see how using .append works for making the list, but why does it not work when I iterate over item in the for loop when creating list_thing (I hope this is clear)

Ohhhhh you COULD do this but I prefer my way:

def string_factory(dicts, string):
  list_thing = []
  for item in dicts:
    formatted_string = string.format(**item)
    list_thing.append(formatted_string)
  return list_thing
Maximilian Richly
Maximilian Richly
4,872 Points

Ok, I think I understand. Thank you for your help :)

1 Answer

You are doing a great job, keep it up! However, you are overthinking. There is no need for "temp_dict". Also, instead of

list_thing[item] = 'Something here'

You should just use append like this:

list_thing.append('Something here')

The complete code is:

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

Hope that helps! ~xela888

Maximilian Richly
Maximilian Richly
4,872 Points

Thank you. I understand the answer now. But why does .format() not work?