converting a value in a dictionary to a list

To avoid the error, simply replace the

if type(recipe[key]) != list:

to

if type(recipe[key]) == str:

Or better,

if isinstance(value, str):

You get the error from trying to use the tokenisation function on certain values, because there are values in the dicts that are indeed of type float, for example, the value of the 'rating' key.

If the tokenization function returns a list of sentences, this should work:

def matching(query):
    token_list = tokenisation(query)
    matching_recipes = []
    
    for recipe in recipes:
        recipe_tokens = []
        
        for value in recipe.values():
            if isinstance(value, str):
                recipe_tokens.append(value)
                continue
            for sentence in value:
                recipe_tokens.extend(tokenisation(sentence))
                
        if all([tl in recipe_tokens for tl in token_list]):
            matching_recipes.append(recipe)

    return matching_recipes

If it returns a list of words:

def matching(query):
    token_list = tokenisation(query)
    matching_recipes = []
    
    for recipe in recipes:
        recipe_tokens = []
        
        for value in recipe.values():
            if isinstance(value, str):
                value = tokenisation(value)
            for sentence in value:
                recipe_tokens.extend(tokenisation(sentence))
                
        if all([tl in recipe_tokens for tl in token_list]):
            matching_recipes.append(recipe)

    return matching_recipes

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top