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 trialMaximilian Richly
4,872 PointsHelp!! list indices must be integers or slices, not dict
it says: list indices must be integers or slices, not dict
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
Maximilian Richly
4,872 Pointsah 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
4,872 Pointsah 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)
Alexander Davison
65,469 PointsOhhhhh 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
4,872 PointsOk, I think I understand. Thank you for your help :)
1 Answer
Alexander Davison
65,469 PointsYou 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
4,872 PointsThank you. I understand the answer now. But why does .format() not work?
Alexander Davison
65,469 PointsAlexander Davison
65,469 PointsWhat do you mean?