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 trialAsif Choudhury
2,086 PointsHow to iterate over a LIST of dictionaries? I know how to iterate over items in a dictionary though.
I know how to iterate items in a dictionary in a for loop:
for k,v in dixonary.items(): print(k,v) But I am struggling to figure out the way to iterate a list of dictionary.
Please help.
# Example:
# values = [{"name": "Michelangelo", "food": "PIZZA"}, {"name": "Garfield", "food": "lasagna"}]
# string_factory(values)
# ["Hi, I'm Michelangelo and I love to eat PIZZA!", "Hi, I'm Garfield and I love to eat lasagna!"]
template = "Hi, I'm {name} and I love to eat {food}!"
1 Answer
Mike Wagner
23,559 PointsSurprisingly enough, it's not all that different to iterate over a list of dictionaries.
for dict_entity in dict_list:
will handle each individual dictionary in the list of dictionaries just as if they were individual items in a list or any other iterable. The slightly more thought involved portion is what to do with those dictionaries as we handle them. The challenge wants to use the **kwarg functionality to unpack the values from each dictionary into the template string using the keywords in the placeholders. Here is a pretty good write-up on args and kwargs in Python that might help you understand what we're expected to do in the challenge a little better.
In our above for-loop we establish where we're sourcing the keywords from to match the string template dict_entity
so we give that to our format operation like so
template.format(**dict_entity)
this will result in a string that matches expectation for one of the dictionaries. Since the challenge expects us to return a list of all the strings this function will generate, we'll have to set up a list at the beginning of the function. Then we would append this freshly formatted string into the list (since it wasn't asking for any particular order). After we've run the for-loop to completion, we'll have a list full of neatly formatted strings
["Hi, I'm Michelangelo and I love to eat PIZZA!", "Hi, I'm Garfield and I love to eat lasagna!"]
which we'll return at the end of the function. I didn't want to do it all for you, and since you said you knew how to iterate over a dictionary, I assume you'll be able to work the final product out on your own. If you run into any issues, I can flesh this out a bit more to provide a more.. example-filled answer. Good luck!