Home > Back-end >  Function that checks if values in a list are the same as specific value lists in a dictionary?
Function that checks if values in a list are the same as specific value lists in a dictionary?

Time:04-10

I want to make a function that takes a list of strings and a dictionary as inputs. If any strings in the list match a set of values in the dictionary, they should return a key corresponding to those values.

An example input would look something like available_dishes(ingredients, recipes). Where

ingredients = ['Fish','Rice','Eggs','Ketchup']
recipes = {'Sushi':['Fish','Rice','Seaweed'],'Grilled_Fish':['Fish'],'Omurice':['Eggs','Rice','Ketchup']}

Because the list only has the necessary ingredients for grilled fish and omurice, this would return the output: ['Grilled_Fish','Omurice']. Specifically, the results should appear in the order that the keys appear in the dictionary.

What I'm Trying

In my attempt, I have isolated one of the lists in the list of dictionary values. I tried focusing on one list so that I might understand how the rest of them might function. What I’ve made isn’t necessarily a function but a group of variables I wanted to try interpreting.

recipe_ingredients = list(recipes.values())

for i in ingredients:
    if i in recipe_ingredients[0]:
        print(i)

Unfortunately, for now, my knowledge of python is limited so this only returns the matching ingredients between the two lists: Fish Rice. I’m still somewhat inexperienced with for loops, so I’d like to see how this could be done using them as well as if statements. If possible, could this be done without the use of list comprehension?

CodePudding user response:

You can use all() to check if recipe has all available ingredients:

ingredients = ["Fish", "Rice", "Eggs", "Ketchup"]
recipes = {
    "Sushi": ["Fish", "Rice", "Seaweed"],
    "Grilled_Fish": ["Fish"],
    "Omurice": ["Eggs", "Rice", "Ketchup"],
}

out = [k for k, v in recipes.items() if all(i in ingredients for i in v)]
print(out)

Prints:

['Grilled_Fish','Omurice']

Without list-comprehension:

out = []
for k, v in recipes.items():
    if all(i in ingredients for i in v):
        out.append(k)

print(out)

CodePudding user response:

Sets are your friends. They are an unordered collection of unique items, like the ingredients of a recipe. First I have turned your lists into sets:

my_ingredients = {'Fish', 'Rice', 'Eggs', 'Ketchup'}
recipes = {'Sushi': {'Fish', 'Rice', 'Seaweed'},'Grilled_Fish': {'Fish'}, 'Omurice': {'Eggs',  'Rice', 'Ketchup'}}

You can then check that the ingredients of a recipe are a subset of your ingredients. Here it is how to use that condition in a list comprehension:

>>> [food for food, ingredients in recipes.items() if ingredients.issubset(my_ingredients)]
['Grilled_Fish', 'Omurice'] 
  • Related