Home > Software design >  count number of missing items required comparing dictionaries in python
count number of missing items required comparing dictionaries in python

Time:12-28

Given a list:

list_essentials = [strawberry, chocolate, tomatoe]

a dictionary with ingredients I currently have:

d = {chocolate:3, strawberry:1, beaf:3}

and a more complex dictionary with the recipes and items per ingredients:

dictionary_recipes = {"cheesecake":{"chocolate":3, "strawberry":4},"strawberry cake":{"sugar":3, "strawberry":2} "lasagna":{"beaf":2, "tomatoe":1}
}

I want to output a dictionary that adds to the elements of the list list_essentials the number of items I need if I wanted to be able to make all the recipes.

The expected output I am looking for in this example is:

new_dict = {strawberry: 5, chocolate: 0, tomatoe: 1}

For strawberry for example I already have 1 but I need 6 to make all recipes, so the number of items I still need is 5

I tried this but the output is not correct:

for elements in list_essentials:
 new_dict={}
 for i, v in d.items():
  for a, b in dictionary_recipes.items():
   if v = 0:
    new_dict.append(b)
   if v > 0:
    new_dict.append(v-b)    
print(new_dict)

CodePudding user response:

i know the code is ineffecient but it works

list_essentials = ['strawberry', 'chocolate', 'tomatoe']
current = {'chocolate':3, 'strawberry':1, 'beaf':3}
required = {"cheesecake":{"chocolate":3, "strawberry":4},"strawberry cake":{"sugar":3, "strawberry":2}, "lasagna":{"beaf":2, "tomatoe":1}}
list_required = required.values()
output = {}
for i in list_essentials:
    output[i] = 0
for i in list_required:
    for a in i:
        if a in list_essentials:
            output[a]  = i[a]
for i in current:
    if i in list_essentials:
        output[i] -= current[i]
        if (output[i] - current[i]) < 0:
            output[i] = 0
        
print(output)

CodePudding user response:

You set your new_dict (witch should hold the total amount of ingredients needed, I think?) to an empty dict for every elements in list_essentials, instead of innitialising it just once.
an working example would e.g. be:

list_essentials = ["strawberry", "chocolate", "tomatoe"]
current_ingredients = {"chocolate":3, "strawberry":1, "beaf":3}
res = {}
for t in list_essentials:
    res[t] = 0
dictionary_recipes = {"cheesecake":{"chocolate":3, "strawberry":4},"strawberry cake":{"sugar":3, "strawberry":2}, "lasagna":{"beaf":2, "tomatoe":1}}
for essential_item in list_essentials:
    for recipe in dictionary_recipes.values():
        if essential_item in recipe.keys():
            res[essential_item]  = recipe[essential_item]
print("total needed items = ", res)
for k in res.keys():
    if k in current_ingredients.keys():
        res[k] -= current_ingredients[k]
print("needed items - current items = ", res)
exit(0)
  • Related