How do i check if the "name" property of any element in drink_list matches any string in a seperate list (str_list)?
drink_list = [
{
"name": "Rum & Coke",
"ingredients": {
"rum": 50,
"coke": 150
}
}, {
"name": "Gin & Tonic",
"ingredients": {
"gin": 50,
"tonic": 150
}
}]
str_list = ['Gin & Tonic’, 'Daquiri']
CodePudding user response:
If you want to keep a list of all the names, do something like that:
>>> l = []
>>> for i in drink_list:
... if i['name'] in str_list:
... l.append(i['name'])
...
>>> l
['Gin & Tonic']
You can also append and keep the whole drink dictionary, if you append i:
l.append(i)
Can also use a list comprehension:
>>> [i['name'] for i in drink_list if i['name'] in str_list]
['Gin & Tonic']
CodePudding user response:
drink_list = [
{
"name": "Rum & Coke",
"ingredients": {
"rum": 50,
"coke": 150
}
}, {
"name": "Gin & Tonic",
"ingredients": {
"gin": 50,
"tonic": 150
}
}]
str_list = ['Gin & Tonic', 'Rum & Coke', 'Daquiri']
// make an empty list
found_list = []
// iterate over drink_list and check if value is in str_list or not
for drink in drink_list:
if drink["name"] in str_list:
found_list.append(drink["name"]) // append matched value in found_list
print(found_list) // prints desired output in list
Output:
['Rum & Coke', 'Gin & Tonic']
