Reputation: 27
I have a Python dictionary containing recipes. I have to find key values inside it and then return results depending on where those keys where found.
recipes = {
'recipe1':{
'name': 'NAME',
'components': {
'1':{
'name1':'NAME',
'percent':'4 %'
},
'2':{
'name2':'NAME',
'percent':'3 %'
},
'3':{
'name3':'NAME',
'percent':'1 %'
},
},
'time':'3-5 days',
'keywords':['recipe1', '1','etc']
}
}
Each recipe has a list of keywords
. How can I lookup a recipe based on its keywords
and some search input? Upon finding a recipe, I would need to return the name components and time that are specific for that recipe.
Upvotes: 0
Views: 143
Reputation: 9144
Do like below
list = ['etc', 'cc', 'ddd']
for x, y in recipes.items():
for m in y['keywords']:
if m in list:
print('Name : ' + y['name'])
print('Components : ')
for i in y['components'].keys():
print(str(i), end=' ')
for j in y['components'][i]:
print(j + " " + y['components'][i][j], end=' ')
print('')
print('\nTime: ' + str(y['time']))
Output:
Name : NAME
Components :
1 name1 NAME percent 4 %
2 name2 NAME percent 3 %
3 name3 NAME percent 1 %
Time: 3-5 days
Upvotes: 0
Reputation: 5039
Given some input in a variable called search
, you can do the following:
for v in recipes.values():
if search in v['keywords']:
# Found the recipe of interest.
return v['components'], v['time']
Unfortunately, the way you are currently storing data prevents you from taking advantage of the O(1)
lookup time in your dictionary. (This could affect performance if you have several recipes in the recipes
dictionary.) So you'll have to iterate over the key-value pairs in recipes
to find a recipe, unless you refactor your data structures.
Upvotes: 2