ametcalf
ametcalf

Reputation: 1

looping through a list of dictionaries to get a certain key

I want to loop through the list(locations) of dictionaries(Home, Work) and if oranges is < 1, then add that dictionary to the empty list (store). How do I do this? Here is my code set up below:

Home = { 'oranges': 0, 'apples': 2, 'bananas': 1 } Work = { 'oranges': 1, 'apples': 0, 'bananas': 4 }

locations = [Home, Work]

store = []

Upvotes: 0

Views: 35

Answers (1)

mhawke
mhawke

Reputation: 87064

This will do it using a list comprehension. It iterates over the dictionary list locations and tests the value of the 'orange' key for each dictionary:

Home = { 'oranges': 0, 'apples': 2, 'bananas': 1 }
Work = { 'oranges': 1, 'apples': 0, 'bananas': 4 }
locations = [Home, Work]

store = [d for d in locations if 'oranges' in d and d.get('oranges') < 1]

>>> store
[{'apples': 2, 'oranges': 0, 'bananas': 1}]

This takes care not to include dictionaries that do not have 'orange' as a key.

Note that you should use lower case variable names such as home and work.

Upvotes: 2

Related Questions