pythondictionary

storing and retrieving images in dictionary - python


Can anyone tell me how to store images in python dictionary (dict), and how to retrieve images from the dictionary based on the key value ?


Solution

  • It is better to store images in files and then reference them with a filename:

    pictures = {'mary': '001.jpg', 'bob', '002.jpg'}
    filename = pictures['mary']
    with open(filename. 'rb') as f:
        image = f.read()
    

    That said, if you want to store images directly in a dictionary, just add them:

    pictures = {}
    
    with open('001.jpg', 'rb') as f:
         image = f.read()
    pictures['mary'] = image
    

    Images aren't special, they are just data.