Given a list:
JavaScript
x
2
1
list_essentials = [strawberry, chocolate, tomatoe]
2
a dictionary with ingredients I currently have:
JavaScript
1
2
1
d = {chocolate:3, strawberry:1, beaf:3}
2
and a more complex dictionary with the recipes and items per ingredients:
JavaScript
1
3
1
dictionary_recipes = {"cheesecake":{"chocolate":3, "strawberry":4},"strawberry cake":{"sugar":3, "strawberry":2} "lasagna":{"beaf":2, "tomatoe":1}
2
}
3
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:
JavaScript
1
2
1
new_dict = {strawberry: 5, chocolate: 0, tomatoe: 1}
2
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:
JavaScript
1
10
10
1
for elements in list_essentials:
2
new_dict={}
3
for i, v in d.items():
4
for a, b in dictionary_recipes.items():
5
if v = 0:
6
new_dict.append(b)
7
if v > 0:
8
new_dict.append(v-b)
9
print(new_dict)
10
Advertisement
Answer
i know the code is ineffecient but it works
JavaScript
1
19
19
1
list_essentials = ['strawberry', 'chocolate', 'tomatoe']
2
current = {'chocolate':3, 'strawberry':1, 'beaf':3}
3
required = {"cheesecake":{"chocolate":3, "strawberry":4},"strawberry cake":{"sugar":3, "strawberry":2}, "lasagna":{"beaf":2, "tomatoe":1}}
4
list_required = required.values()
5
output = {}
6
for i in list_essentials:
7
output[i] = 0
8
for i in list_required:
9
for a in i:
10
if a in list_essentials:
11
output[a] += i[a]
12
for i in current:
13
if i in list_essentials:
14
output[i] -= current[i]
15
if (output[i] - current[i]) < 0:
16
output[i] = 0
17
18
print(output)
19