storing and retrieving images in dictionary - python

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.


Personally, if I had to go down that road, I would load the image into a variable and then add it to dictionary as a value {key:value} as you would with any other variable. If you are using Pygame you don't need to load it as a file and can already load the image using pygame.image.load(file) .

Just a note : Loading image files, especially JPEGs in binary as suggested is tricky. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files.

As with images in dictionaries, you could even nest a list of images in the dictionary (along with a key), Having a list is one way to easily animate by looping the list within each key. {'key1' : ['value1', 'value2','value2']}

Remember however that once you pack a variable inside a dictionary, the value of the variable would not change and remain constant inside the dictionary, unless you specifically update the dictionary. Just updating the value outside of the dictionary, would not affect it's original value that it was given when it was placed inside the dictionary.

Example: (using pygame, load images into a list, and nest it into a dictionary for recall)

def load_image(file):
    """loads and prepares image from data directory"""
    file = os.path.join(main_dir, 'data', file)
    try:
        surface = pygame.image.load(file)
    except pygame.error:
        raise SystemExit('Could not load image "%s" %s'%(file, pygame.get_error()))
    return surface.convert()

def load_images(*files):
    """ function to load a list of images through an *arg and return a list 
    of images"""
    images = []
    for file in files:
        images.append(load_image(file))
    return images

bomb_images = load_images('bomb.gif', 'bomb2.gif','bomb3.gif')
explosion_images = load_images('ex1.gif', 'ex2.gif', 'ex3.gif')
# now all the images are inside a list and you can pack them in a dictionary

image_dict = {'bomb' : bomb_images, 'explode' :explosion_images} 
# to call the image would be the same as you call any value from the dict
bombs = image_dict['bomb']

image_ready_for_blit = bombs[0]
# changing the slice position allows animation loops [0]