Returning a list of filenames with keywords associated with it

I'm not sure why I get an empty list I test this function. Can anyone please help me fix this?

def find_images_with_keyword(key_dict, keywords_list):
'''(dict of {str: list of str}, list of str) -> list
Given a keyword_dictionary and a list of keywords,
return the list of filenames associated with the given keywords.
The list of filenames should include all filenames having one or more
of the specified keywords(ie, a filename may be associated with only one,
not all of the keywords in the list).
>>> find_images_with_keyword({'dog': ['1.png', '2.png'], 'animal': ['1.png',  '3.png']}, ['dog', 'animal'])
  ['1.png', '2.png', '3.png']
'''
new_list = []
for keyword in key_dict.items():
    for filename in keywords_list:
        if keyword == filename:
            new_list.append(filename)
return new_list

1 answer

  • answered 2017-11-15 00:39 Mad Lee

    Try this

    def find_images_with_keyword(key_dict, keywords_list):
        '''(dict of {str: list of str}, list of str) -> list
        Given a keyword_dictionary and a list of keywords,
        return the list of filenames associated with the given keywords.
        The list of filenames should include all filenames having one or more
        of the specified keywords(ie, a filename may be associated with only one,
        not all of the keywords in the list).
        >>> find_images_with_keyword({'dog': ['1.png', '2.png'], 'animal': ['1.png',  '3.png']}, ['dog', 'animal'])
          ['1.png', '2.png', '3.png']
        '''
    
        found_imgs = set()
        for keyword, value in key_dict.items():
            if keyword in keywords_list:
                found_imgs = found_imgs.union(set(value))
        return found_imgs
    
    print find_images_with_keyword({'dog': ['1.png', '2.png'], 'animal': ['1.png', '3.png']}, ['dog', 'animal'])
    

    EDIT: add list version based on yours.

    def find_images_with_keyword(key_dict, keywords_list):
        new_list = []
        for item in key_dict.items():
            key, filenames = item
            if key in keywords_list:
                for filename in filenames:
                    if filename not in new_list:  # add this
                        new_list.append(filename)
        return new_list