Jimmy
Jimmy

Reputation: 21

Verify if items of list are present in a another list of dictionaries

I have a list that looks like this:

fruits = [apple,grapes,banana]

I have another list called: attributes :

[{'name': 'apple', 'color': 'red', 'price': '2'},
 {'name': 'orange', 'color': 'orange', 'price': '6'},
 {'name': 'grapes', 'color': 'green', 'price': '3'},
 {'name': 'mango', 'color': 'yellow', 'price': '8'},
 {'name': 'banana', 'color': 'yellow', 'price': '4'}]

I want to be able to check if the elements of the list fruits are present in the list attributes and if yes, put the corresponding prices in a separate list.

So the resulting list as the output should look like [2,3,4]

This is the piece of code I tried but it has errors

price = []
for attribute in attributes:
    if attribute['name'] is in fruits:
        print (attribute['price'])
        price.append(attribute['price'])
        price = list(set(price))

Upvotes: -1

Views: 31

Answers (1)

Hai Vu
Hai Vu

Reputation: 40783

Your code will work if you remove the word is. This is where the error is.

price = []
for attribute in attributes:
    if attribute['name'] in fruits:
        print (attribute['price'])
        price.append(attribute['price'])
        price = list(set(price))

Upvotes: 0

Related Questions