Python Forum
Dictionnary indexing error - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Dictionnary indexing error (/thread-34876.html)



Dictionnary indexing error - Ander - Sep-10-2021

Hello, i try to animate a character with 3 frames named "playerf1", 2 and 3, in a "player animation" folder.
I use pygame but that is not at the origin of the problem ^^.

So, i have this error :
self.image2 = self.images[self.current_image]
KeyError: 1

I found that this error occurs when the thing i want to find doesnt exist but right here i dont know why it can not find the images in the dictionnary...
Thanks for your help ^^

class AnimateSprite(pygame.sprite.Sprite):

    def __init__(self, sprite_name):
        super().__init__()
        #load the player
        self.image2 = pygame.image.load(sprite_name + '.png')

        self.current_image = 0
        self.images = animations.get(sprite_name)

    # animate the sprite
    def animate(self):
        self.current_image += 1
        if self.current_image >= len(self.images):
            self.current_image = 0

        self.image2 = self.images[self.current_image]


def load_animation_images(sprite_name):
    images = []

    path = "player animation/" + sprite_name
    for num in range(1, 3):
        image_path = path + str(num) + '.png'
        #pygame.image.load is used to load the image_path
        images.append(pygame.image.load(image_path))

    return images

animations = {
    'player': load_animation_images('playerf')
}



RE: Dictionnary indexing error - Yoriz - Sep-10-2021

The code shown doesn't give enough away to help solve the issue.
The thread title Dictionnary indexing error but I don't see any sign of a dictionary.
The function load_animation_images return a list of pygame images but is never shown as being called in the code.
In the class AnimateSprite > __init__ images is assigned to animations.get(sprite_name) which is not shown so its unknown what it returns


RE: Dictionnary indexing error - Ander - Sep-10-2021

Oh no so sorry the code didn't copy right, i updated my first message, it was missing the end of the program.

animations = {
    'player': load_animation_images('playerf')
}
Here is the dictionnary !


RE: Dictionnary indexing error - Yoriz - Sep-10-2021

If I strip out the pygame code I get the following
class AnimateSprite:
    def __init__(self, sprite_name):
        super().__init__()
        # load the player
        self.image2 = f"{sprite_name}.png"

        self.current_image = 0
        self.images = animations.get(sprite_name)

    # animate the sprite
    def animate(self):
        self.current_image += 1
        if self.current_image >= len(self.images):
            self.current_image = 0

        self.image2 = self.images[self.current_image]


def load_animation_images(sprite_name):
    images = []

    path = f"player animation/{sprite_name}"
    for num in range(1, 3):
        image_path = f"{path}{num}.png"
        images.append(image_path)

    return images


animations = {"player": load_animation_images("playerf")}
if I add the following it show the contents of the dict
print(animations)
it outputs
Output:
{'player': ['player animation/playerf1.png', 'player animation/playerf2.png']}
Note you have the range stop set as 3 so it won't include 3, if you want 1 2 & 3 use range(1, 4)

Adding the following it successfully cycles through the list of image file paths
animate_sprite = AnimateSprite("player")
for _ in range(5):
    animate_sprite.animate()
    print(animate_sprite.image2)
Output:
player animation/playerf2.png player animation/playerf1.png player animation/playerf2.png player animation/playerf1.png player animation/playerf2.png

In what way are you calling your code to get the error as your code doesn't show anything being called.


RE: Dictionnary indexing error - Ander - Sep-10-2021

I call the code in another file to start animating the player :

self.animate()
And yes i tried without pygame stuff and everything works so idk why it cannot find in the dictionnary with the pygame stuff


RE: Dictionnary indexing error - Yoriz - Sep-10-2021

When it gets to the line that you have the error it is not a dictionary it is a list, it is getting an item by index, not key.
self.image2 = self.images[self.current_image]
self.images = animations.get(sprite_name) is using the key sprite_name to get the corresponding value.
Your dictionary only has the key player which contains the list returned by load_animation_images("playerf")

To get a key error on that line, your dictionary animations must contain other key values and you are calling AnimateSprite with something other than player and the dictionary is returning another dictionary not a list.


RE: Dictionnary indexing error - Ander - Sep-10-2021

Yes but sprite_name = player so its like:

self.images = animation.get(player)

I tried to replace all the sprite_name by just player and the error is still here