Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionnary indexing error
#1
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')
}

Attached Files

Thumbnail(s)
   
Reply
#2
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
Reply
#3
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 !
Reply
#4
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.
Reply
#5
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
Reply
#6
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.
Reply
#7
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to change 0 based indexing to 1 based indexing in python..?? Ruthra 2 4,270 Jan-22-2020, 05:13 PM
Last Post: Ruthra
  python dictionnary Omar_Yatim 3 2,752 Dec-08-2019, 05:12 AM
Last Post: scidam
  Dictionnary brackets issue Reldaing 1 1,782 Nov-10-2019, 11:54 PM
Last Post: ichabod801
  Access to the elements of a dictionnary Reims 1 1,601 Oct-02-2019, 12:48 PM
Last Post: SheeppOSU
  from Json Time Serie file to python dictionnary Reims 1 1,986 Sep-11-2019, 08:17 AM
Last Post: DeaD_EyE
  convert a json file to a python dictionnary of array Reims 2 2,201 Sep-10-2019, 01:08 PM
Last Post: Reims
  dictionnary lateublegende 1 2,414 Apr-29-2019, 09:10 PM
Last Post: Yoriz
  Why do we need setdefault() method for dictionnary? DJ_Qu 3 2,660 Apr-21-2019, 11:00 AM
Last Post: Gribouillis
  Json dictionnary on Redis katsu707 1 2,409 Dec-04-2018, 11:59 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020