How do i check if a property of any dict in a list matches any string from another list?

0

Issue

How do i check if the "name" property of any element in drink_list matches any string in a separate 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']

Solution

    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’]

Answered By – rawbeen72

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More