Home > Net >  Return key (from dictionary) if values are present in a list
Return key (from dictionary) if values are present in a list

Time:10-05

I have a dictionary:

meals = {'Pasta Bolognese' : ['pasta', 'tomato sauce', 'ground beef'],
    'Cold Salad' : ['greens', 'tomato'],
    'Warm Salad' : ['greens', 'tomato', 'corn', 'chickpeas', 'quinoa'],
    'Sandwich' : ['bread', 'turkey slices', 'cheese', 'sauce']}

and a list:

ingredients = ['bread', 'chickpeas', 'tomato', 'greens']

I want to get a key from dictionary if all its values are present in the list. So for current situation I want to get 'Cold Salad' since both 'greens' and 'tomato' are in the list.

CodePudding user response:

You could use:

>>> next((k for k, v in meals.items() if set(v).issubset(ingredients)))
'Cold Salad'
>>> 

Notice that this code uses a generator with next, also to have a more efficient way to have multiple in statements, instead of all and a loop with in, I used set.issubset to check if all values in one set is a subset of the other.

If there might be no matches, add a None at the end:

next((k for k, v in meals.items() if set(v).issubset(ingredients)), None)

Or anything, you could replace None with anything i.e. "No Match".

CodePudding user response:

You can use list comprehension as follows:

meals = {'Pasta Bolognese' : ['pasta', 'tomato sauce', 'ground beef'],
        'Cold Salad' : ['greens', 'tomato'],
        'Warm Salad' : ['greens', 'tomato', 'corn', 'chickpeas', 'quinoa'],
        'Sandwich' : ['bread', 'turkey slices', 'cheese', 'sauce'], 
        'Another Item': ['greens', 'bread']}

ingredients = ['bread', 'chickpeas', 'tomato', 'greens']

output = [key for key, value in meals.items() if set(value).issubset(ingredients)]

print(output)

Result:

['Cold Salad', 'Another Item']

You will notice I have added Another Item to test that more than one matching item will be returned.

  • Related