0

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.

ndmeiri
  • 4,979
  • 12
  • 37
  • 45
  • Why is `keywords` nested inside of `recipe1`? Shouldn't it be up a level? Or possibly even outside of the dictionary? And are the `keywords` supposed to be like the keys of the `dict`? – pushkin Mar 14 '18 at 19:02
  • @pushkin No, every recipe would have its own set of keywords associated with it, just like every recipe has its own name. – chepner Mar 14 '18 at 19:16
  • @chepner oh, duh. I forgot what the word keywords meant outside of a programming context. Thanks – pushkin Mar 14 '18 at 19:22
  • I believe your question has an answer here: https://stackoverflow.com/questions/22162321/search-for-a-value-in-a-nested-dictionary-python – John Stanesa Mar 14 '18 at 19:24

2 Answers2

2

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.

ndmeiri
  • 4,979
  • 12
  • 37
  • 45
0

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
Morse
  • 8,258
  • 7
  • 39
  • 64