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!

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 Functional Python The Lambda Lambada Lambda

Alex Rendon
Alex Rendon
7,498 Points

How can I access to a list of dictionaries?

I think that it is the problem.

meals.py
meals = [
    {'name': 'cheeseburger',
     'calories': 750},
    {'name': 'cobb salad',
     'calories': 250},
    {'name': 'large pizza',
     'calories': 1500},
    {'name': 'burrito',
     'calories': 1050},
    {'name': 'stir fry',
     'calories': 625}
]

high_cal = filter(lambda cal: cal > 1000, meals['calories'])

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,389 Points

Alex, you're on the right track. filter() will iterate over an object applying the filter function to each item. In this challenge you are iterating over the object meals as a list of dictionary. The lambda function needs to inspect each of these dictionaries for the necessary condition. In this case, it is dict_in['calories'] > 1000:

high_cal = filter(lambda dict_in: dict_in['calories'] > 1000, meals)
Alex Rendon
Alex Rendon
7,498 Points

Oh, I wasn't calling the key in the right part, This help me so much. Thanks

Josh Keenan
Josh Keenan
19,651 Points

To access a key within a dictionary it's easy!

meals = [
    {'name': 'cheeseburger',
     'calories': 750},
    {'name': 'cobb salad',
     'calories': 250},
    {'name': 'large pizza',
     'calories': 1500},
    {'name': 'burrito',
     'calories': 1050},
    {'name': 'stir fry',
     'calories': 625}
]

There's the list of dictionaries, let's say you want to know how many calories a cobb salad has. You go to that position in the list.

meals[1]

Then you choose the key you want to access, and in this case it's the 'calories' key.

meals[1]['calories']

Hope this helps, post to this thread again if you need any more help!

Alex Rendon
Alex Rendon
7,498 Points

Thanks Josh, your comment is very helpful !